[英]goroutine leak with context timeout?
In the code below, a client is putting a string on a service's input channel and listening for a reply on either an output or an error channel. 在下面的代码中,客户端将字符串放在服务的输入通道上,并在输出或错误通道上侦听答复。
The context is set with a 5ms timeout. 上下文设置为5毫秒超时。
func (s service) run() {
<-s.input
go func() {
select {
case <-s.ctx.Done():
s.errs <- errors.New("ctx done")
return
}
}()
time.Sleep(10 * time.Millisecond)
s.output <- 42
fmt.Println("run exit")
}
The code times out correctly (due to the 10ms sleep) and outputs 代码正确超时(由于睡眠时间为10ms)并输出
error: ctx done
However, the "run exit" is never printed. 但是,从不打印“运行出口”。
Question : Is there a goroutine leak with processes stuck on 问题 :是否存在goroutine泄漏且进程卡在进程上
s.output <- 42
Go Playground example 去游乐场的例子
Context has timeout of 5 milliseconds and you sleep for 10 millisecond before this line s.output <-42
is run. 上下文的超时时间为5毫秒,您睡了10毫秒,然后运行此行s.output <-42
。 So the context is timeout first and error occurs, that correct, but take a look at main
function: 因此上下文首先是超时,然后发生错误,这种错误是正确的,但请看一下main
功能:
select {
case o := <-s.output:
fmt.Println("output: ", o)
case err := <-s.errs:
fmt.Println("error: ", err)
}
The select
statement has reached case err := <-s.errs
so it will break the select and go to the end of main
function => program exit Even if s.output <- 42
is call simultaneously with s.errs <- errors.New("ctx done")
only one case has reached in select
statement, if you need to reach second case, put a loop around select statement select
语句已达到大小写err := <-s.errs
因此它将中断选择并转到main
函数的末尾=>程序退出即使s.output <- 42
与s.errs <- errors.New("ctx done")
同时调用s.errs <- errors.New("ctx done")
在select
语句中仅达到一种情况,如果需要达到第二种情况,则在select语句周围放一个循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.