package main
import (
"fmt"
)
type A struct{
exit chan bool
}
func (a *A) f(){
select{
//the routine process
//quit
case <- a.exit:
fmt.Println("-----over-----")
a.exit <- true
fmt.Println(" over ")
}
}
func main() {
a := A{}
go a.f()
a.exit = make(chan bool)
a.exit <- true
}
我想運行 muti goroutines,我想讓 main func 注意到其他 goroutine 退出。這是我的代碼,但是select里面的程式塊,程式只輸出“-----over-----”,沒有“ over ”,代碼有什么問題?感謝你幫助。
uj5u.com熱心網友回復:
您的程式阻塞,因為這是您撰寫的內容,請考慮以下操作順序:
maingoroutine 啟動a.fgoroutine。a.f阻止嘗試從 nil 通道讀取a.exit。main設定a.exit為無緩沖通道,a.f現在阻止從新通道讀取,這是允許的。main將一個值寫入a.exit并a.f從中讀取值a.exit,這會同步 goroutine,現在下層被阻塞。a.f現在阻止嘗試寫入 unbuffereda.exit,這將永遠不會解除阻止,因為沒有人會再次嘗試從通道讀取。main現在退出并導致所有其他 goroutine 退出,這可能發生在第 5 步之前。
所以你的程式從不輸出的原因 over 是:
- 你的
a.fgoroutine 阻塞在a.exit <- true因為沒有其他 goroutine 會從通道讀取這個值。 - 您的
maingoroutine 可能會在a.f完成作業之前退出并終止整個程式。
我想你是在問如何在 goroutine 完成后退出 main,這是最簡單的例子:
package main
import (
"fmt"
)
type A struct {
exit chan struct{}
}
func (a *A) f() {
defer close(a.exit) // Close the chanel after f() finishes, closed channels yield the zero-value so <-a.exit will unblock
fmt.Println(" over ")
}
func main() {
a := A{}
go a.f()
a.exit = make(chan struct{})
<-a.exit
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365602.html
