dongshuzui0335 2014-02-13 14:23
浏览 25
已采纳

select语句的默认情况持续执行

Similar: golang: goroute with select doesn't stop unless I added a fmt.Print()

I am writing a code in go, where a goroutine keeps receiving and processing requests on a socket. To stop the execution of current goroutine, I send true to a channel from some other goroutine, for which the current goroutine keeps listening in select statement.

But the problem here is that even after sending signal on channel, default block keeps executing forever. And case block is never executed. Following is the code snippet I am having problem with.

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
            }
        }

I have searched for the problem and found solutions as

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.

As per suggestion, I tried putting a print statement in default case, also I tried putting a sleep statement in default case. But nothing is working.

Is there any way to make this work? Also is it possible to achieve the intended by completely avoiding select statement?

  • 写回答

1条回答 默认 最新

  • dro60731 2014-02-13 21:15
    关注

    If you do responder.Recv without a timeout, your code will block there forever and you won't get to the default part. So I guess try setting a timeout ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端