sách gpt4 ăn đã đi

go - 带 channel 的 WaitGroup goroutines

In lại 作者:IT王子 更新时间:2023-10-29 01:57:35 24 4
mua khóa gpt4 giày nike

我正在从博客中学习 WaitGroup https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/

Mã số:

gói chính

nhập khẩu (
"fmt"
"đồng bộ"
"thời gian"
)

hàm main() {
messages := make(chan int)
var wg đồng bộ.WaitGroup

// you can also add these one at
// a time if you need to

wg.Add(3)
đi func() {
defer wg.Done()
time.Sleep(time.Second * 3)
messages <- 1
}()
đi func() {
defer wg.Done()
time.Sleep(time.Second * 2)
messages <- 2
}()
đi func() {
defer wg.Done()
time.Sleep(time.Second * 1)
messages <- 3
}()
đi func() {
for i := range messages {
fmt.Println(i)
}
}()

wg. Chờ()
}

我认为它应该按顺序打印 3、2 和 1。但是它只打印了 3, 2 却少了 1,这是什么问题?

你可以在 https://play.golang.org/p/kZCvDhykYM 上树它

câu trả lời hay nhất

在最新的 messages <- 1 之后, 延期 wg.Xong()被调用释放wg. Chờ()在程序结束时程序退出。当程序退出时,所有 goroutine 都会被杀死,因此打印 goroutine 没有机会打印最新值。

如果你输入类似 time.Sleep(time.Second * 1) 的内容在wg.Xong()之后您将能够看到所有输出行。

关于go - 带 channel 的 WaitGroup goroutines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46703863/

24 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress