猿问

golang所有goroutines都睡着了 - 死锁

运行跟随 golang 片段时出现错误。我认为进度将在 wg.Wait() 处阻塞,直到 go 例程结束。那么该值将从 c1 获得。但它可能不会按预期进行。


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!


一只甜甜圈
浏览 155回答 3
3回答

心有法竹

写入c1永远不会执行,因为读取c1是在之后wg.Wait(),它将停止直到c1被写入。所以 main goroutine 等待,wg.Wait()嵌套 goroutine 等待c1write。c1您可以使通道缓冲,或在单独的 goroutine 上等待读取。

HUWWW

在 Golang 中,无缓冲通道上的写操作是阻塞的。从文档中可以清楚地看到。您的执行被阻止在c1&nbsp;<-&nbsp;"one"延期声明defer&nbsp;wg.Done()从不执行。

米脂

在您的代码中,您正在使用一个无缓冲的通道,该通道会阻塞直到接收器接收到“一个”。在这种情况下,代码不会超过 wg.Wait() 因为 wg.Done() 永远不会被执行。我想这就是你所追求的。func main() {c1 := make(chan string)//var c1 chan stringgo func() {&nbsp; &nbsp; fmt.Printf("go routine begin\n")&nbsp; &nbsp; time.Sleep(1 * time.Second)&nbsp; &nbsp; c1 <- "one"&nbsp; &nbsp; fmt.Printf("go routine done\n")}()fmt.Printf("done c1: %v\n", <-c1)fmt.Printf("out\n")}
随时随地看视频慕课网APP

相关分类

Go
我要回答