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

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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)