1 回答

TA貢獻1847條經驗 獲得超7個贊
當 main 返回時,Go 程序退出。在這種情況下,您的程序在退出之前不會等待最終的“世界”在另一個 goroutine 中打印出來。
以下代碼(playground)將確保 main 永遠不會退出,從而允許其他 goroutine 完成。
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 2; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
select{}
}
您可能已經注意到,這會導致死鎖,因為程序無法繼續(xù)前進。您可能希望添加一個通道或一個 sync.Waitgroup 以確保程序在其他 goroutine 完成后立即干凈地退出。
例如(游樂場):
func say(s string, ch chan<- bool) {
for i := 0; i < 2; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
if ch != nil {
close(ch)
}
}
func main() {
ch := make(chan bool)
go say("world", ch)
say("hello", nil)
// wait for a signal that the other goroutine is done
<-ch
}
- 1 回答
- 0 關注
- 171 瀏覽
添加回答
舉報