douqiao5552 2018-12-12 00:42
浏览 36
已采纳

Goroutines选择带范围循环[关闭]

I want to spawn a goroutine to listen to two channels of type chan int and chan os.Signal. I want the behavior to be specific depending on what's received on either channels. Meaning some os.Signal may cause os.exit() and some may not, some int received through chan int may print a statement and some may call a function, so I need this gorountine to be always running since the behaviors are different. And I'd like this to be all handed by one function.

I'm having a hard time figuring out how to achieve this syntactically. It doesn't seem like I can have range loops inside of a select block nor does it seem like I can have a select block inside a range loop. I can't find any resource online on this. Can someone give me an example?

  • 写回答

1条回答 默认 最新

  • dongqiu3709 2018-12-12 01:05
    关注

    You can put a select statement in a for loop (this is one of the examples in the language spec). Unlike a for...range loop, this will let you read from both channels. It also won't automatically terminate if one of the channels closes. When you receive from a closed channel, a closed channel is always ready to receive and always produces a zero value, and there is a two-valued form of it that tells you whether the channel is open or not.

    Your function might loosely look like

    func HandleStuff(numbers <-chan int, signals <-chan os.Signal) {
        var goingToExit bool
        for {
            select {
            case n := <-numbers:
                if n == 0 {
                    fmt.Printf("zero
    ")
                } else if n == 1 {
                    goingToExit = true
                }
            case sig, ok := <-signals:
                if !ok { // the channel is closed
                    return
                } else if goingToExit {
                    os.Exit(0)
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等