Go 使用通道结束死循环
可以使用一个带有 'stop' 通道的 'select' 语句来结束死循环。在循环中,我们可以使用 'select' 语句来等待多个通道的消息,当 'stop' 通道接收到消息时,我们可以通过 'break' 语句来退出循环。
以下是一个示例代码:
package main
import (
"fmt"
"time"
)
func main() {
stop := make(chan bool)
go func() {
time.Sleep(5 * time.Second)
stop <- true
}()
for {
select {
case <-stop:
fmt.Println('Received stop signal')
return
default:
fmt.Println('Running...')
time.Sleep(1 * time.Second)
}
}
}
在上面的代码中,我们创建了一个 'stop' 通道,并在一个单独的 goroutine 中等待 5 秒钟后向 'stop' 通道发送消息。在主 goroutine 中,我们使用一个 'select' 语句来等待 'stop' 通道的消息。如果接收到消息,我们打印一条消息并使用 'return' 语句退出循环。如果没有接收到消息,我们打印一条运行中的消息并等待 1 秒钟。
当运行上面的程序时,它将输出类似以下的消息:
Running...
Running...
Running...
Running...
Running...
Received stop signal
原文地址: https://www.cveoy.top/t/topic/lrVi 著作权归作者所有。请勿转载和采集!