在继续之前让Go运行所有的goroutine

qyzbxkaa  于 2023-05-20  发布在  Go
关注(0)|答案(1)|浏览(133)

我需要Golang调度器在继续之前运行所有的goroutines,运行时。Gosched()不能解决。
问题是go例程可以运行得如此之快,以至于start()中的“select”在de stopStream()中的“select”之后运行,然后“case <-chanStopStream:”接收方没有准备好发送方“case retChan <- true:”。结果是,当这种情况发生时,结果与stopStream()挂起时的行为相同
运行此代码https://go.dev/play/p/DQ85XqjU2Q_z多次,您将看到这两个响应Expected response when NOT hang:

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")
    }
}
hfyxw5xn

hfyxw5xn1#

在继续执行当前的goroutine之前,没有办法运行所有其他的goroutine。
通过确保goroutine不会在stopStream上阻塞来解决这个问题:

选项1:将chanStopStream更改为buffered channel。这确保了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://go.dev/play/p/xWg42TO_fIW

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

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

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

https://go.dev/play/p/lNfT6qzrMmO

相关问题