优雅地终止 Goroutine
在 Go 中,goroutine 提供并发性,允许多个任务同时执行。有时,有必要终止一个 goroutine,例如当我们需要优雅地关闭一个应用程序时。
考虑以下代码:
<code class="go">func startsMain() { go main() } func stopMain() { //kill main } func main() { //infinite loop }</code>
在这种情况下,主 goroutine 运行无限循环,我们希望在 stopMain 函数中停止它。我们如何实现这一目标?
解决方案在于使用通道在 goroutine 之间进行通信。这是一个改进的代码片段:
<code class="go">var quit chan struct{} func startLoop() { quit = make(chan struct{}) go loop() } func stopLoop() { close(quit) } // BTW, you cannot call your function main, it is reserved func loop() { for { select { case <-quit: return // better than break default: // do stuff. I'd call a function, for clarity: do_stuff() } } }</code>
我们引入了一个struct{}类型的退出通道,它可以保存一个空的结构体值。
这种机制允许我们通过退出通道向 goroutine 发送信号来优雅地终止无限循环。
以上是如何优雅地终止 Go 中的 Goroutine?的详细内容。更多信息请关注PHP中文网其他相关文章!