登录
首页 >  Golang >  Go问答

如何通知另一个 goroutine 停止?

来源:stackoverflow

时间:2024-04-01 20:54:34 453浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《如何通知另一个 goroutine 停止?》,涉及到,有需要的可以收藏一下

问题内容

我有2个goroutines,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)
  ...
}

我知道上面的代码不安全,但是如果我使用通道从 gf 发送停止,则 f 在从通道读取时将被阻止,这是我想避免的。在 go 中执行此操作的安全且惯用的方法是什么?


解决方案


使用通道关闭来通知其他 goroutine 某个条件。使用带有默认子句的 select 以避免在检查条件时发生阻塞。

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)
}

它也可以将值发送到容量大于零的通道,但关闭通道可以扩展到支持多个 goroutine。

方法是使用带有default子句的select语句(参见this example)。

所以 f 看起来像:

func f(stop chan bool) {
  select {
    case s := <- stop:
      if s {
        return
      }
    default:
      do_something()
  }
}

以上就是《如何通知另一个 goroutine 停止?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>