在 go 中,取消长时间运行的 context 可通过调用 context.cancelfunc 返回的函数实现,以下为取消 context 的步骤:创建一个带超时时间的子上下文。在 goroutine 中循环监听上下文是否被取消,并在取消时停止运行。在主 goroutine 中调用 cancelfunc 取消上下文。

如何在 Go 中取消长时间运行的 Context
在 Go 中,context.Context 是一个用来管理请求和取消操作的类型。在长期运行的操作中,正确处理上下文至关重要,以避免资源泄漏和死锁。
取消 Context
立即学习“go语言免费学习笔记(深入)”;
取消上下文通过调用 context.CancelFunc 返回的函数来完成。这将立即发送取消信号,这可以由其他 goroutine 监听。
package main
import (
"context"
"fmt"
"time"
)
func main() {
// 创建带超时时间的上下文
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// 在 goroutine 中模拟长时间运行
go func() {
for {
select {
case <-ctx.Done():
// 当上下文被取消时,停止运行
fmt.Println("操作已取消")
return
default:
// 继续运行
}
}
}()
// 在主 goroutine 中模拟操作
time.Sleep(5 * time.Second)
fmt.Println("主操作已完成")
// 取消上下文
cancel()
}在这个例子中:
context.Background() 创建一个新的顶层上下文(无超时或取消)。context.WithTimeout() 创建一个带超时时间的子上下文。cancel 函数返回一个 context.CancelFunc,用于取消上下文。cancel 函数取消上下文。实战案例
在以下实战案例中,我们使用 Context 来管理对远程数据库的请求。如果请求在一定时间内没有完成,我们将取消请求以避免资源浪费:
package main
import (
"context"
"database/sql"
"fmt"
"time"
)
func main() {
db, err := sql.Open("postgres", "user:password@host:port/database")
if err != nil {
panic(err)
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 把 Context 传入数据库操作中
row := db.QueryRowContext(ctx, "SELECT name FROM users WHERE id = 1")
var name string
err = row.Scan(&name)
if err != nil {
if err == context.Canceled {
// 请求已取消
fmt.Println("请求已超时")
} else {
// 其他错误处理
fmt.Println(err)
}
} else {
fmt.Println("获取用户名成功:", name)
}
}以上就是Golang 函数:如何取消长时间运行的上下文的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号