gpt4 book ai didi

go - 如何通知另一个 goroutine 停止?

转载 作者:行者123 更新时间:2023-12-01 22:38:51 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to stop a goroutine

(7 个回答)


2年前关闭。




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

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

最佳答案

使用 channel close 来通知其他 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)
}

它还可以向容量大于零的 channel 发送值,但关闭 channel 扩展到支持多个 goroutine。

关于go - 如何通知另一个 goroutine 停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58442033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com