在继续之前要求 Go 运行所有 goroutine

2024年 2月 11日 31.0k 0

在继续之前要求 go 运行所有 goroutine

在进行并发编程时,我们经常遇到需要等待所有goroutine完成后再继续执行的情况。在Go语言中,我们可以通过使用WaitGroup来实现这个目标。WaitGroup是一个计数信号量,可以用于等待一组goroutine的完成。在继续之前,我们需要调用WaitGroup的Wait方法,这样可以确保所有的goroutine都已经完成了任务。在本文中,我们将介绍如何正确使用WaitGroup来管理goroutine的执行顺序。

问题内容

我需要 golang 调度程序在继续之前运行所有 goroutine,runtime.gosched() 无法解决。

问题在于 go 例程运行速度太快,以至于 start() 中的“select”在 stopstream() 内的“select”之后运行,然后“case

运行此代码https://go.dev/play/p/dq85xqju2q_z
很多时候你会看到这两个回应
未挂起时的预期响应:

2009/11/10 23:00:00 start
2009/11/10 23:00:00 receive chan
2009/11/10 23:00:03 end

登录后复制

挂起时的预期响应,但挂起时的响应却不是那么快:

2009/11/10 23:00:00 start
2009/11/10 23:00:00 default
2009/11/10 23:00:01 timer
2009/11/10 23:00:04 end

登录后复制

代码

package main

import (
"log"
"runtime"
"sync"
"time"
)

var wg sync.WaitGroup

func main() {
wg.Add(1)
//run multiples routines on a huge system
go start()
wg.Wait()
}
func start() {
log.Println("Start")
chanStopStream := make(chan bool)
go stopStream(chanStopStream)
select {
case 登录后复制

解决方法

在继续执行当前 goroutine 之前,没有办法运行所有其他 goroutine。

通过确保 goroutine 不会在 stopstream 上阻塞来修复问题:

选项 1:将 chanstopstream 更改为缓冲通道。这确保了 stopstream 可以无阻塞地发送值。

func start() {
log.println("start")
chanstopstream := make(chan bool, 1) // 登录后复制

https://www.php.cn/link/56e48d306028f2a6c2ebf677f7e8f800

选项 2:关闭通道而不是发送值。通道始终可以由发送者关闭。在关闭的通道上接收返回通道值类型的零值。

func start() {
log.Println("Start")
chanStopStream := make(chan bool) // buffered channel not required
go stopStream(chanStopStream)
...

func stopStream(retChan chan bool) {
...
close(retChan)
}

登录后复制

https://www.php.cn/link/a1aa0c486fb1a7ddd47003884e1fc67f

以上就是在继续之前要求 Go 运行所有 goroutine的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论