我如何通知另一个goroutine停止?
我有两个goroutine,我如何通知另一个goroutine停止?,go,Go,我有两个goroutine,g用于检测当f应该停止时的情况,f在执行实际处理之前检查它是否应该在每次迭代中停止。在Java等其他语言中,我会使用线程安全的共享变量,如以下代码: func g(stop *bool) { for { if check_condition() { *stop = true return } } } func f(stop *bool) { for { if *stop { return
g
用于检测当f
应该停止时的情况,f
在执行实际处理之前检查它是否应该在每次迭代中停止。在Java等其他语言中,我会使用线程安全的共享变量,如以下代码:
func g(stop *bool) {
for {
if check_condition() {
*stop = true
return
}
}
}
func f(stop *bool) {
for {
if *stop {
return
}
do_something()
}
}
func main() {
var stop = false
go g(&stop)
go f(&stop)
...
}
我知道上面的代码不安全,但如果我使用通道从
g
发送stop到f
,f
在从通道读取时会被阻止,这是我想要避免的。在Go中这样做的安全惯用方法是什么?方法是使用select语句和default子句(请参阅)
所以f
看起来像:
func f(stop chan bool) {
select {
case s := <- stop:
if s {
return
}
default:
do_something()
}
}
func f(停止切换){
挑选{
案例s:=使用channel close将条件通知其他goroutine。在检查条件时,使用select和default子句以避免阻塞
func g(stop chan struct{}) {
for {
if check_condition() {
close(stop)
return
}
}
}
func f(stop chan struct{}) {
for {
select {
case <-stop:
return
default:
do_something()
}
}
}
func main() {
var stop = make(chan struct{})
go g(stop)
go f(stop)
}
func g(stop chan结构{}){
为了{
如果检查_条件(){
关闭(停止)
返回
}
}
}
func f(stop chan结构{}){
为了{
挑选{
在g
发送stop之前会阻止f
的case。对不起,可能我误解了。不,它不会阻止。这是做你想做的事情的标准方法。当你想让f停止做某事时,将true推到stop频道。