dongyun3805 2017-07-05 18:14 采纳率: 0%
浏览 68
已采纳

如果一个goroutine完成,控制goroutine关闭的规范方法是什么?

I have a slice of struct that defines a task, each task is run in a goroutine, and I want all go goroutines to stop whenever the first one complete a task via the signal task.signalComplete

Currently I have the following.

for _, task := range taskList {
    go func(task *myTask, firstCompleteSignal chan<- bool) {
        for {
            select {
                // When the task completes, it emit signalComplete
                case <-task.signalComplete:
                    firstCompleteSignal<-true
                    return
            }
        }

    }(task, firstCompleteSignal)
}

for {
    select {
    case <-firstCompleteSignal:
        // manually stop all go thread
        return
    }
}

Is this canonical?

Or is there library to do this for me like sync.WaitGroup for waiting all goroutine to be done?

  • 写回答

1条回答 默认 最新

  • dongxian0421 2017-07-05 18:32
    关注

    The common idiom is to have a Done channel shared between the calling code and the goroutines.

    Then each goroutine would check that channel via a select each time they send a new value to the calling code.

    You can find a good example in Go's blog:

    https://blog.golang.org/pipelines

    (look for "Explicit Cancellation" there)

    Later, they incorporated a context package to the standard library, and that is now the most "standard" way to manage cancellation of goroutines.

    You can find a good example in the documentation for the package itself:

    https://golang.org/pkg/context/#example_WithCancel

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

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?