gpt4 book ai didi

go - 如何停止可能正在运行或未运行的 goroutine?

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:55 27 4
gpt4 key购买 nike

我有一个 go func,如果它在默认情况下运行,我想停止它。以下方法在 quit <- true 处被阻止如果 go func 已经返回。

quit := make(chan bool)
go func() {
for {
select {
case <- quit:
return
default:
// Do other stuff and return if complete.
}
}
}()

// Do stuff

// Quit goroutine
quit <- true

最佳答案

关闭退出 channel 而不是发送值。循环将退出,因为在关闭的 channel 上接收返回零值。

此外,将 channel 声明为 chan struct{} 以指示 channel 值对程序不重要:

quit := make(chan struct{})
go func() {
for {
select {
case <- quit:
return
default:
// Do other stuff and return if complete.
}
}
}()

// Do stuff

// Quit goroutine
close(quit)

如果你需要摆脱“其他东西”,那么将退出 channel 传递给“其他东西”并时不时检查一下:

select {
case <- quit:
return
default:
}
... keep going

如果您所做的不仅仅是此答案中的第一个片段,那么您应该考虑使用标准 context取消信号包。

关于go - 如何停止可能正在运行或未运行的 goroutine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47165730/

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