卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

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

在继续之前要求 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 <-chanStopStream:
        log.Println("receive chan")
    case <-time.After(time.Second): //if stopStream hangs do not wait more than 1 second
        log.Println("TIMER")
        //call some crash alert
    }
    time.Sleep(3 * time.Second)
    log.Println("end")
    wg.Done()
}

func stopStream(retChan chan bool) {
    //do some work that can be faster then caller or not
    runtime.Gosched()
    //time.Sleep(time.Microsecond) //better solution then runtime.Gosched()
    //time.Sleep(2 * time.Second) //simulate when this routine hangs more than 1 second
    select {
    case retChan <- true:
    default: //select/default is used because if the caller times out this routine will hangs forever
        log.Println("default")
    }
}

解决方法

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

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

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

func start() {
    log.println("start")
    chanstopstream := make(chan bool, 1) // <--- buffered channel
    go stopstream(chanstopstream)
    ...
}

func stopstream(retchan chan bool) {
    ...
    // always send. no select/default needed.
    retchan <- true
}

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

卓越飞翔博客
上一篇: 为什么 net/http 不考虑超过 30 秒的超时持续时间?
下一篇: `go build` 的输出标志 `-o` 有副作用吗?
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏