如何停止一个goroutine
1、使用通道
func main() {
done := make(chan bool)
go func() {
for {
select {
case <-done:
return // 当done被关闭时,退出goroutine
default:
// 执行任务...
}
}
}()
// 在需要停止goroutine的时候
close(done) // 发送信号让goroutine退出
}
使用context
import (
"context"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
select {
case <-ctx.Done():
return // 当ctx被取消时,退出goroutine
default:
// 执行任务...
}
}
}()
// 在需要停止goroutine的时候
cancel() // 取消context,goroutine会收到取消信号
}