使用context实现Goroutine超时与取消,通过WithTimeout或WithCancel创建上下文,结合select监听ctx.Done()及时终止任务,传递context以传播取消信号,并用defer cancel()防止资源泄露。

Goroutine超时控制和取消,简单来说,就是防止你的goroutine跑太久,或者在不需要的时候及时停止它,避免资源浪费。这很重要,尤其是在处理网络请求、数据库查询等耗时操作时。
解决方案
Goroutine超时控制和取消的核心在于使用
context
context
超时控制: 使用
context.WithTimeout
context.WithDeadline
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel() // 确保取消 context,释放资源
result := make(chan string, 1)
go func() {
// 模拟耗时操作
time.Sleep(3 * time.Second)
result <- "操作完成"
}()
select {
case res := <-result:
fmt.Println("结果:", res)
case <-ctx.Done():
fmt.Println("超时:", ctx.Err()) // 输出 context.DeadlineExceeded
}
}在这个例子中,
context.WithTimeout
ctx.Done()
select
case <-ctx.Done()
defer cancel()
取消: 使用
context.WithCancel
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
result := make(chan string, 1)
go func() {
// 模拟耗时操作
for i := 0; i < 5; i++ {
select {
case <-ctx.Done():
fmt.Println("任务取消")
return // 必须return,否则会继续执行
default:
fmt.Println("执行中...", i)
time.Sleep(1 * time.Second)
}
}
result <- "操作完成"
}()
time.Sleep(3 * time.Second)
cancel() // 取消 context
select {
case res := <-result:
fmt.Println("结果:", res)
case <-ctx.Done():
fmt.Println("取消:", ctx.Err()) // 输出 context.Canceled
}
time.Sleep(1 * time.Second) // 等待 goroutine 退出,否则可能主进程先退出
}这里,
cancel()
ctx.Done()
return
context传递: 将context作为参数传递给goroutine。
这允许goroutine访问取消信号和截止时间,并将其传递给其他函数或goroutine。这是一种优雅地传播取消信号的方式。
优雅地处理goroutine取消意味着在收到取消信号后,goroutine能够清理资源、保存状态,并安全地退出。
检查ctx.Err()
ctx.Err()
使用select
select
ctx.Done()
清理资源: 在退出goroutine之前,确保释放所有资源,例如关闭文件、释放锁等。
发送完成信号: 可以使用channel通知调用者goroutine已完成,即使是被取消。
设置合理的超时时间: 超时时间应该足够长,以便操作能够完成,但又不能太长,以免浪费资源。这需要根据具体情况进行调整。
使用context.WithTimeout
context.WithDeadline
context.WithTimeout
context.WithDeadline
传播context: 将context作为参数传递给所有相关的函数和goroutine,以便取消信号能够传播到整个调用链。
避免死锁: 在处理超时或取消信号时,要小心避免死锁。例如,不要在等待channel发送或接收数据的同时等待context取消。
Goroutine泄露是指goroutine永远阻塞,无法退出,导致资源浪费。
总是使用defer cancel()
cancel()
避免无限循环: 确保goroutine中的循环能够退出,即使没有收到取消信号。
使用带缓冲的channel: 如果goroutine需要向channel发送数据,但接收者可能已经退出,则可以使用带缓冲的channel,以避免发送者阻塞。
使用sync.WaitGroup
sync.WaitGroup
wg.Wait()
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
numTasks := 5
for i := 0; i < numTasks; i++ {
wg.Add(1) // 增加计数器
go func(taskID int) {
defer wg.Done() // goroutine 完成时减少计数器
defer fmt.Println("Task", taskID, "finished") // 确保任务结束时打印消息
fmt.Println("Task", taskID, "started")
time.Sleep(time.Duration(taskID) * time.Second) // 模拟不同耗时的任务
}(i)
}
wg.Wait() // 等待所有 goroutine 完成
fmt.Println("All tasks completed")
}这个例子中,
wg.Add(1)
wg.Done()
wg.Wait()
defer fmt.Println("Task", taskID, "finished")总之,Goroutine的超时控制和取消是Go并发编程中非常重要的概念。理解和掌握这些技术可以帮助你编写更健壮、更可靠的并发程序。
以上就是Golanggoroutine超时控制与取消方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号