Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我如何通知另一个goroutine停止?_Go - Fatal编程技术网

我如何通知另一个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

我有两个goroutine,
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频道。