类似:golang: goroute with select doesn't stop unless I added a fmt.Print()
我正在用 go 编写代码,其中 goroutine 不断接收和处理套接字上的请求。为了停止当前 Goroutine 的执行,我将 true
从其他 Goroutine 发送到 channel ,当前 Goroutine 在 select
语句中继续监听该 channel 。
但这里的问题是,即使在 channel 上发送信号后,default
block 也会永远执行。并且 case
block 永远不会被执行。以下是我遇到问题的代码片段。
for {
select{
//goroutine should return when something is received on channel 's.stopInbox'
case <-s.stopInbox:
fmt.Println("stopInbox")
return
//keep receiving and processing requests until anything is received on channel 's.stopInbox'
default:
fmt.Println("default case")
msg, err := responder.Recv(0)
if err != nil {
fmt.Println("Error receiving message", err.Error())
break
}
envelope := msgToEnvelope(msg)
s.inbox <- &envelope
}
}
我已经搜索了问题并找到了解决方案
With a default statement select will run the default statement every time there is nothing to read from the channels. And because of this, scheduler will never get a chance to schedule another goroutine. Putting the
fmt.Print
statement in is allowing the scheduler to schedule other goroutines.
根据建议,我尝试在默认情况下放置打印语句,也尝试在默认情况下放置 sleep 语句。但没有任何效果。
有什么办法可以实现这个功能吗?另外,完全避免 select
语句是否可以达到预期目的?
最佳答案
如果您在没有超时的情况下执行responder.Recv
,您的代码将永远阻塞在那里,并且您将无法到达default
部分。所以我想尝试设置超时;)
关于loops - select 语句的默认情况继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21756877/