如果一个 goroutine 已完成,控制 goroutine 关闭的规范方法是什么?
What is the canonical way to control the closing of goroutine if one goroutine is complete?
我有一段定义任务的结构,每个任务都是 运行 在一个 goroutine 中,我希望所有的 goroutines 在第一个通过信号 [=11= 完成任务时停止]
目前我有以下
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
}
}
这是规范的吗?
或者是否有像 sync.WaitGroup 等待所有 goroutine 完成的库为我做这件事?
常见的习惯用法是在调用代码和 goroutine 之间共享一个 Done
通道。
然后每个 goroutine 每次都通过 select
检查那个通道
向调用代码发送一个新值。
你可以在 Go 的博客中找到一个很好的例子:
https://blog.golang.org/pipelines
(在那里寻找 "Explicit Cancellation")
后来,他们将 context
包合并到标准库中,这是现在管理 goroutine 取消的最 "standard" 方式。
您可以在包本身的文档中找到一个很好的例子:
我有一段定义任务的结构,每个任务都是 运行 在一个 goroutine 中,我希望所有的 goroutines 在第一个通过信号 [=11= 完成任务时停止]
目前我有以下
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
}
}
这是规范的吗?
或者是否有像 sync.WaitGroup 等待所有 goroutine 完成的库为我做这件事?
常见的习惯用法是在调用代码和 goroutine 之间共享一个 Done
通道。
然后每个 goroutine 每次都通过 select
检查那个通道
向调用代码发送一个新值。
你可以在 Go 的博客中找到一个很好的例子:
https://blog.golang.org/pipelines
(在那里寻找 "Explicit Cancellation")
后来,他们将 context
包合并到标准库中,这是现在管理 goroutine 取消的最 "standard" 方式。
您可以在包本身的文档中找到一个很好的例子: