gpt4 book ai didi

go - 在 Golang 中,如何使用 channel 处理多个 goroutine

转载 作者:IT王子 更新时间:2023-10-29 01:57:21 25 4
gpt4 key购买 nike

我正在考虑在 Golang 中使用 for 循环同时启动 1000 个 goroutine。
问题是:我必须确保每个 goroutine 都已执行。
是否可以使用 channel 来帮助我确保这一点?

结构是这样的:

func main {
for i ... {
go ...
ch?
ch?
}

最佳答案

正如@Andy 提到的,您可以使用sync.WaitGroup 来实现这一点。下面是一个例子。希望代码是不言自明的。

package main

import (
"fmt"
"sync"
"time"
)

func dosomething(millisecs int64, wg *sync.WaitGroup) {
defer wg.Done()
duration := time.Duration(millisecs) * time.Millisecond
time.Sleep(duration)
fmt.Println("Function in background, duration:", duration)
}

func main() {
arr := []int64{200, 400, 150, 600}
var wg sync.WaitGroup
for _, n := range arr {
wg.Add(1)
go dosomething(n, &wg)
}
wg.Wait()
fmt.Println("Done")
}

关于go - 在 Golang 中,如何使用 channel 处理多个 goroutine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48000448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com