dongtaihui5131 2016-07-12 03:03
浏览 19
已采纳

从通道读取时未检测到“死锁”

How do I deal with a situation where undetected deadlock occurs when reading results of execution of uncertain number tasks from a channel in a complex program, e.g. web server?

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UTC().UnixNano())

    results := make(chan int, 100)

    // we can't know how many tasks there will be
    for i := 0; i < rand.Intn(1<<8)+1<<8; i++ {
        go func(i int) {
            time.Sleep(time.Second)
            results <- i
        }(i)
    }

    // can't close channel here 
    // because it is still written in
    //close(results)

    // something else is going on other threads (think web server)
    // therefore a deadlock won't be detected
    go func() {
        for {
            time.Sleep(time.Second)
        }
    }()

    for j := range results {
        fmt.Println(j)
        // we just stuck in here
    }
}

In case of simpler programs go detects a deadlock and properly fails. Most examples either fetch a known number of results, or write to the channel sequentially.

  • 写回答

1条回答 默认 最新

  • dongyao1915 2016-07-12 03:03
    关注

    The trick is to use sync.WaitGroup and wait for the tasks to finish in a non-blocking way.

    var wg sync.WaitGroup
    
    // we can't know how many tasks there will be
    for i := 0; i < rand.Intn(1<<8)+1<<8; i++ {
        wg.Add(1)
        go func(i int) {
            time.Sleep(time.Second)
            results <- i
            wg.Done()
        }(i)
    }
    
    // wait for all tasks to finish in other thread
    go func() {
        wg.Wait()
        close(results)
    }()
    
    // execution continues here so you can print results
    

    See also: Go Concurrency Patterns: Pipelines and cancellation - The Go Blog

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退