context.WithCancel用于优雅终止goroutine,调用cancel()后ctx.Done()关闭,所有监听该信号的任务退出。

在Go语言中,context.WithCancel 是控制并发任务生命周期的重要工具。当你启动多个goroutine并希望在某个条件满足或发生错误时主动取消它们,使用
WithCancel
调用
context.WithCancel()
ctx, cancel := context.WithCancel(context.Background()) defer cancel() // 确保在函数退出时释放资源
这里的
cancel
ctx.Done()
每个并发任务应定期检查 context 是否已被取消。通常通过 select 监听
ctx.Done()
立即学习“go语言免费学习笔记(深入)”;
示例:启动多个工作协程for i := 0; i < 3; i++ {
go func(id int) {
for {
select {
case <-ctx.Done():
fmt.Printf("worker %d 收到取消信号\n", id)
return
default:
fmt.Printf("worker %d 正在工作...\n", id)
time.Sleep(500 * time.Millisecond)
}
}
}(i)
}
每个 worker 在每次循环中检查 context 状态。如果取消发生,立即退出,避免浪费资源。
你可以在任意时刻调用
cancel()
time.Sleep(2 * time.Second) cancel() // 触发取消,所有worker将退出
此时,所有正在运行的 worker 都会从
select
ctx.Done()
context.WithTimeout
context.WithDeadline
ctx.Err()
基本上就这些。合理使用
context.WithCancel
以上就是Golang使用context.WithCancel取消并发任务的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号