【发布时间】:2017-08-27 06:20:33
【问题描述】:
我有一个示例代码(您可以在Go Playground 上找到它):
package main
import (
"fmt"
"sync"
"time"
)
func main() {
messages := make(chan int)
var wg sync.WaitGroup
var result []int
// you can also add these one at
// a time if you need to
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Second * 1)
messages <- 1
}()
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Second * 1)
messages <- 2
}()
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Second * 1)
messages <- 3
}()
go func() {
for i := range messages {
fmt.Println(i)
result = append(result, i)
}
}()
wg.Wait()
fmt.Println(result)
}
我得到了这个输出:
2
1
[2 1]
我想我知道它为什么会发生,但我无法解决它。 WaitGroup 中有 3 个项目,我的意思是三个 goroutine,第 4 个 groutine 使用来自通道的数据。当最后一个 groutine 说 wg.Done() 时,程序结束了,因为 wg.Wait() 表示每个 goroutine 都完成了,最后一个 goroutine 结果第四个 goroutine 不能消费,因为程序结束了。我尝试在第四个函数中使用 wg.Add(1) 和 wg.Done() 加一,但在这种情况下我遇到了死锁。
【问题讨论】:
-
参见例如stackoverflow.com/questions/42085173/channel-deadlock-in-go/… - 这与您的示例非常相似。