实现思路
- 创建一个
context.Context
和 context.CancelFunc
,通过 context.WithCancel
函数,CancelFunc
用于取消 Context
。
- 将
context.Context
传递给每个 goroutine
,每个 goroutine
应定期检查 Context
的 Done
通道,当通道关闭时,表示需要取消任务。
- 在任何一个
goroutine
检测到异常时,调用 CancelFunc
,这会关闭 Context
的 Done
通道,其他 goroutine
检测到通道关闭后,停止执行。
关键代码示例
package main
import (
"context"
"fmt"
"time"
)
func task(ctx context.Context, id int) {
for {
select {
case <-ctx.Done():
fmt.Printf("goroutine %d received cancel signal, exiting\n", id)
return
default:
fmt.Printf("goroutine %d is working\n", id)
time.Sleep(100 * time.Millisecond)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
// 启动多个goroutine
for i := 1; i <= 3; i++ {
go task(ctx, i)
}
// 模拟某个goroutine出现异常
go func() {
time.Sleep(500 * time.Millisecond)
fmt.Println("simulating an error in a goroutine")
cancel() // 取消所有goroutine
}()
time.Sleep(1000 * time.Millisecond)
}