从频道读取时未检测到"死锁"

san*_*mai 4 deadlock channel go

当从复杂程序(例如Web服务器)中的通道读取执行不确定数量任务的结果时,如何处理未检测到死锁的情况?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果程序更简单,则检测到死锁并正确失败.大多数示例要么获取已知数量的结果,要么按顺序写入通道.

san*_*mai 7

诀窍是使用sync.WaitGroup并等待任务以非阻塞方式完成.

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
Run Code Online (Sandbox Code Playgroud)

另请参阅:Go并发模式:管道和取消 - Go Blog