golang 中可以使用 context 包来传递上下文信息:使用 context.background() 创建一个新的上下文。使用 context.withvalue() 将值添加到上下文中。使用 ctx.value() 获取上下文中存储的值。

在并发程序中传递上下文信息至关重要,它允许在不同 goroutine 中访问共享数据。这对于日志记录、追踪、错误处理和传递中间数据很有用。
Go 标准库提供了一个 context 包,它提供了用于管理上下文信息的类型和函数。
要创建一个新的 context.Context,请使用 context.Background():
立即学习“go语言免费学习笔记(深入)”;
ctx := context.Background()
您可以使用 context.WithValue() 将值添加到上下文中:
ctx = context.WithValue(ctx, "key", "value")
您可以在任何地方获取上下文中存储的值:
value := ctx.Value("key")假设我们有一个 goroutine池,它执行并行任务。我们要在每个 goroutine 中记录任务的开始和结束时间。
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// 创建 goroutine 池
pool := make(chan func())
for i := 0; i < 10; i++ {
go func(ctx context.Context, i int) {
fmt.Println("Task", i, "started")
// 这里我们使用了上下文里的时间戳来计算任务耗时
start := time.Now()
ctx = context.WithValue(ctx, "start", start)
// 模拟任务执行
time.Sleep(time.Second)
// 获取任务开始时间并计算耗时
start = ctx.Value("start").(time.Time)
fmt.Printf("Task %d ended, took %v\n", i, time.Since(start))
}(ctx, i)
pool <- nil
}
close(pool)
time.Sleep(5 * time.Second)
}在此示例中,我们使用 context.WithValue() 将 start 时间戳添加到上下文中。然后,在 goroutine 中,我们可以通过 ctx.Value() 获取开始时间戳,并计算任务的耗时。
以上就是如何在 Golang 函数中传递上下文信息?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号