登录
首页 >  Golang >  Go问答

等待 goroutine 执行完毕

来源:stackoverflow

时间:2024-03-22 21:57:21 258浏览 收藏

在执行大量 CPU 密集型任务时,本文介绍了一种在 Go 中限制并行 goroutine 数量的方法。它建议使用缓冲通道来控制 goroutine 的执行,确保同时运行的 goroutine 不超过一个指定的限制。该方法通过监控通道中的结果来管理 goroutine 的数量,并在 goroutine 完成时启动新的 goroutine。这种技术有助于避免资源耗尽并提高应用程序的性能。

问题内容

我正在 8 个不同的 goroutine 上运行一个 cpu 密集型脚本。每个 goroutine 都至少需要几分钟才能完成,我想知道这样的事情是否可能:

for i := 0; i < len(input); i += 1 {
  wait_for_number_of_processes_running_to_be_less_than_8
  go calc_math_and_things(input[i])
}

解决方案


您可以使用缓冲通道返回 goroutine 的结果并指示终止,当您从此通道读取数据时,您将启动一个新的 go 例程。类似这样的事情:

const maxnroutine = 8
var routinectr int
var resultch = make(chan int, maxnroutine)

for i := 0; i < len(input); i += 1 {
    if routinectr < maxnroutines {
        go calc_math_and_things(resultch, input[i])
        routinectr++
        continue
    }
    var result = <- resultch // go routine is done, log result and start a new one
    println(result)
    go calc_math_and_things(resultch, intput[i])
}

在你的日常生活中:

func calc_math_and_things(resultCh chan<- int, input byte) {
     // ... do some stuff
     resultCh <- 1
}

理论要掌握,实操不能落!以上关于《等待 goroutine 执行完毕》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>