英文:
What is the canonical way to control the closing of goroutine if one goroutine is complete?
问题
我有一个定义任务的结构体切片,每个任务都在一个goroutine中运行,我希望当第一个任务完成时,所有的goroutine都停止,通过信号task.signalComplete。
目前我有以下代码。
for _, task := range taskList {
	go func(task *myTask, firstCompleteSignal chan<- bool) {
		for {
			select {
                // 当任务完成时,发出signalComplete信号
				case <-task.signalComplete:
					firstCompleteSignal<-true
					return
			}
		}
	}(task, firstCompleteSignal)
}
for {
	select {
	case <-firstCompleteSignal:
		// 手动停止所有的goroutine
		return
	}
}
这样写是否规范?
或者是否有像sync.WaitGroup一样的库可以等待所有的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
得分: 2
常见的做法是在调用代码和goroutine之间共享一个Done通道。
然后每个goroutine在向调用代码发送新值时都会通过select检查该通道。
你可以在Go的博客中找到一个很好的例子:
https://blog.golang.org/pipelines
(在那里搜索“Explicit Cancellation”)
后来,他们将context包纳入了标准库中,这现在是管理goroutine取消的最“标准”方式。
你可以在该包的文档中找到一个很好的例子:
https://golang.org/pkg/context/#example_WithCancel
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论