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

huangapple go评论91阅读模式
英文:

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&lt;- bool) {
		for {
			select {
                // When the task completes, it emit signalComplete
				case &lt;-task.signalComplete:
					firstCompleteSignal&lt;-true
					return
			}
		}

	}(task, firstCompleteSignal)
}

for {
	select {
	case &lt;-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:

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

huangapple
  • 本文由 发表于 2017年7月6日 02:14:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/44933295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定