donglian4879 2018-06-07 15:21
浏览 12

发生状况时停止读取频道的最佳方法

I have a go routine that keeps blocked until a channel receives new data. However, I need to stop the go routine whenever a condition is true. I wonder what is the best way to do this.

I will illustrate the problem with an example code. The first solution I thought was using a select statement and check the condition constantly, like this:

func routine(c chan string, shouldStop func() bool) {
    select {
    case s := <-c:
        doStuff(s)
    default:
        if shouldStop() {
            return
        }
    }
}

However, this approach will force the routine to call shouldStop() every time and never block. I thought this could lead to performance problems, specially because there a lot others routines running.

Another option would be to use a sleep to at least block a little between shouldStop() calls. However, this would not be a perfect solution, since I'd like to call doStuff() in the exact time the channel receives with new data

Lastly, I thought about using a second channel just to achieve this, like:

func routine(c chan string, stop chan bool) {
    select {
    case s := <-c:
        doStuff(s)
    case b := <-stop:
        return
    }
}

While I thought that this might work, this would force me to have an extra channel along with the shouldStop flag. Maybe there is a better solution I'm not aware of.

Any suggestion is appreciated. Thanks.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥16 mybatis的代理对象无法通过@Autowired装填
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示
    • ¥15 求三国群英传pl国战时间的修改方法
    • ¥15 matlab代码代写,需写出详细代码,代价私
    • ¥15 ROS系统搭建请教(跨境电商用途)