loops - select 语句的默认情况继续执行

标签 loops go

类似: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/

相关文章:

elasticsearch - 如何在 Golang 中共享服务连接

php - 长时间运行的 Golang 程序和资源(文件句柄、tcp 连接等)

dns - Go中从IP地址获取域名

c++ - 在树莓派上构建 libtensorflow.so 时出错

loops - 如何在 Windbg 中编写这样的循环?

java - 停止循环时遇到问题

pointers - 在golang中将一个指针转换为另一种类型

python - 将循环打包到函数中以静音变量的Pythonic 方法?

r - 通过随机样本增加加权平均值

python - Python 3-计算器错误处理