dongyun3805
2017-07-05 18:14
浏览 61
已采纳

如果一个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

    点赞 打赏 评论

相关推荐 更多相似问题