问题描述
运行golang片段时出现错误.我认为进度将在wg.Wait()处阻塞,直到go例程结束.那么该值将从c1获得.但是它可能无法按预期进行.
I got an error when running follow golang snippet.I think the progress will block at wg.Wait() until the go routine is over. then the value would be obtained from c1. But it may not proceed as expected.
func main() {
c1 := make(chan string)
//var c1 chan string
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
fmt.Printf("go routine begin\n")
time.Sleep(1 * time.Second)
c1 <- "one"
fmt.Printf("go routine done\n")
}()
wg.Wait()
fmt.Printf("done c1: %v\n", <-c1)
fmt.Printf("out\n")
}
错误信息是
go routine begin
fatal error: all goroutines are asleep - deadlock!
推荐答案
对 c1
的写入将永远不会执行,因为对 c1
的读取是在 wg之后.Wait()
,它将一直停止直到写入 c1
.因此,主要goroutine等待 wg.Wait()
,而嵌套goroutine等待 c1
写入.
The write to c1
will never execute, because the read from c1
is after wg.Wait()
, which will stop until c1
is written to. So main goroutine waits at wg.Wait()
and the nested goroutine waits at c1
write.
您可以缓冲通道,或等待 c1
在单独的goroutine上读取.
You can make the channel buffered, or wait for c1
read on a separate goroutine.
这篇关于golang所有goroutine都处于睡眠状态-死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!