像這裏一樣,我創建了一個go playground示例:sGgxEh40ev,但無法使其工作。如何根據該例程的返回值來停止goroutine
quit := make(chan bool)
res := make(chan int)
go func() {
idx := 0
for {
select {
case <-quit:
fmt.Println("Detected quit signal!")
return
default:
fmt.Println("goroutine is doing stuff..")
res <- idx
idx++
}
}
}()
for r := range res {
if r == 6 {
quit <- true
}
fmt.Println("I received: ", r)
}
輸出:
goroutine is doing stuff..
goroutine is doing stuff..
I received: 0
I received: 1
goroutine is doing stuff..
goroutine is doing stuff..
I received: 2
I received: 3
goroutine is doing stuff..
goroutine is doing stuff..
I received: 4
I received: 5
goroutine is doing stuff..
goroutine is doing stuff..
fatal error: all goroutines are asleep - deadlock!
這可能嗎?我錯在哪裏
您必須結束您的main for循環。正如錯誤告訴你:沒有任何東西到達水庫。 – Volker
@Volker,但即使我做'break'循環的主要,然後做'退出< - 真正的',仍然僵局,你可以幫助創建一個工作場所的例子嗎? – lnshi
在你的程序中,'res < - idx'和'quit < - true'都等待它們的值被接收,導致死鎖。一個更好的使用渠道模式可以在這裏找到(https://play.golang.org/p/uf94rfXkva) –