doupu1949 2014-01-15 08:04
浏览 40
已采纳

如何在select的父级范围内运行的select case中调用goroutine

I am building a data tool that collects data in a stream and operates on it. I have a main routine, a "process manager", which is responsible for creating new routines of an accumulation function. The manager is informed to create the routines based on a channel receive select case which it is running in an infinite for loop (I already have my cancel routine for itself and all of the routines it creates). The problem is that the manager needs to be able to run the goroutine accumulators in its main scope so that they can operate outside of the select and for loop's scope (I want them to keep running while the manager accepts new cases).

cancel := make(chan struct{})
chanchannel := make(chan chan datatype)

func operationManager (chanchannel chan chan datatype, cancel chan struct{}) {
for {
 select {
  case newchan := <- chanchannel:
    go runAccum(newchan, cancel)
  case <- cancel:
    return
 }
}
}

func runAccum(inchan chan datatype, cancel chan struct{}) {
for {
 select {
  case data := <- inchan;
    //do something
  case <- cancel:
    return
 }
}
}

This is a very, very dumbed-down example of my use-case, but I hope it illustrates my problem's component pieces. Let me know if this is possible, feasible, reasonable, inadvisable; And no, this is not how I implemented my teardown haha

  • 写回答

1条回答 默认 最新

  • douxian1892 2014-01-15 09:46
    关注

    There is no "scope" to goroutines. All goroutines are equal. There is "scope" for closures but your goroutines do not span closures. So all your goroutines spanned by go runAccum(newchan, cancel) will be like any other goroutine you span, no matter from where.

    I assume you did not test your solution?

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c