使用context.WithCancel可取消goroutine,调用cancel()后所有监听该context的goroutine通过ctx.Done()收到信号并退出。

在Golang中,
context
使用
context
context.WithCancel
context
CancelFunc
CancelFunc
context
context
package main
import (
"context"
"fmt"
"time"
)
func worker(ctx context.Context, id int) {
for {
select {
case <-ctx.Done():
fmt.Printf("Worker %d: 任务取消\n", id)
return
default:
fmt.Printf("Worker %d: 正在工作中...\n", id)
time.Sleep(time.Second)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
// 启动多个worker goroutine
for i := 1; i <= 3; i++ {
go worker(ctx, i)
}
// 模拟一段时间后取消任务
time.Sleep(3 * time.Second)
fmt.Println("准备取消所有worker...")
cancel()
// 等待一段时间,确保所有worker都已退出
time.Sleep(time.Second)
fmt.Println("所有worker已退出,程序结束")
}在这个例子中,我们创建了一个带有取消功能的
context
worker
context.Done()
cancel()
context
worker
立即学习“go语言免费学习笔记(深入)”;
context.WithTimeout
context
package main
import (
"context"
"fmt"
"time"
)
func longRunningTask(ctx context.Context) {
select {
case <-time.After(5 * time.Second):
fmt.Println("任务完成")
case <-ctx.Done():
fmt.Println("任务超时取消")
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel() // 确保即使任务提前完成,cancel也会被调用
go longRunningTask(ctx)
select {
case <-ctx.Done():
fmt.Println("主程序检测到任务超时")
case <-time.After(6 * time.Second): // 稍微长于longRunningTask,确保其完成或超时
fmt.Println("主程序结束")
}
}在这个例子中,
longRunningTask
context.WithTimeout
context
longRunningTask
defer cancel()
cancel
context.WithValue
context
package main
import (
"context"
"fmt"
)
func processRequest(ctx context.Context) {
userID := ctx.Value("userID")
fmt.Printf("处理请求,用户ID: %v\n", userID)
}
func main() {
ctx := context.WithValue(context.Background(), "userID", "12345")
processRequest(ctx)
}在这个例子中,我们在
context
userID
processRequest
context
userID
context.Value
context
context
context
context
context
context
package main
import (
"context"
"fmt"
"time"
)
func childTask(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("子任务被取消")
case <-time.After(2 * time.Second):
fmt.Println("子任务完成")
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
go childTask(ctx)
time.Sleep(1 * time.Second)
fmt.Println("取消父任务")
cancel()
time.Sleep(1 * time.Second) // 等待子任务退出
}在这个例子中,
childTask
context
context
context
context
childTask
context
context.TODO
context
context
context
cancel
context.Value
context
总而言之,
context
context
以上就是Golang使用context控制并发任务生命周期的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号