面试题答案
一键面试在Go语言中,context
包用于在多个goroutine
之间传递请求上下文并管理请求的生命周期。以下是实现这一需求的步骤及示例代码:
- 创建上下文:通常使用
context.Background()
作为根上下文,然后基于它创建具有取消功能或超时功能的上下文。 - 传递上下文:将上下文作为参数传递给需要管理生命周期的
goroutine
函数。 - 控制结束:通过调用取消函数(
cancel
)或等待上下文超时来结束goroutine
。
示例代码如下:
package main
import (
"context"
"fmt"
"time"
)
func worker(ctx context.Context, id int) {
for {
select {
case <-ctx.Done():
fmt.Printf("Worker %d stopped\n", id)
return
default:
fmt.Printf("Worker %d is working\n", id)
time.Sleep(100 * time.Millisecond)
}
}
}
func main() {
// 创建一个可取消的上下文
ctx, cancel := context.WithCancel(context.Background())
// 启动多个goroutine
for i := 1; i <= 3; i++ {
go worker(ctx, i)
}
// 模拟一些工作
time.Sleep(500 * time.Millisecond)
// 取消上下文,所有goroutine将收到结束信号
cancel()
// 等待所有goroutine结束
time.Sleep(200 * time.Millisecond)
}
在上述代码中:
context.WithCancel(context.Background())
创建了一个可取消的上下文ctx
和取消函数cancel
。worker
函数接收上下文ctx
,在select
语句中监听ctx.Done()
通道,当接收到信号时,goroutine
结束。- 在
main
函数中,启动了3个worker
goroutine
,然后通过调用cancel()
函数来取消上下文,所有worker
goroutine
将收到结束信号并停止工作。