我需要 Golang 调度程序在继续之前运行所有 goroutine,runtime.Gosched() 没有解决。
问题是 go 例程运行得如此之快以至于 start() 中的“select”在 de stopStream() 中的“select”之后运行,然后是“case <-chanStopStream:" receiver is not ready to the sender "case retChan <- true:". The result is that when this happen the result is the same behavior from when stopStream() hangs
运行这段代码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")
}
}
通过更改
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://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)
}