Context 超时控制
难度:⭐⭐ 中等
考点
- context.WithTimeout 使用
- 超时取消传播
- 父 context 取消影响子 context
题目描述
实现带超时控制的请求函数,以及并发请求多个 URL 的函数。
提示
context.WithTimeout返回带截止时间的子 context- 记得
defer cancel()释放资源 - FetchMultiple 中每个 URL 启动一个 goroutine
参考答案(Go)
点击展开参考答案
go
//go:build ignore
package answer
import (
"context"
"sync"
"time"
)
func FetchWithTimeout(ctx context.Context, url string, timeout time.Duration, fetcher func(ctx context.Context, url string) (string, error)) (string, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return fetcher(ctx, url)
}
func FetchMultiple(urls []string, timeout time.Duration, fetcher func(ctx context.Context, url string) (string, error)) map[string]string {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
var mu sync.Mutex
results := make(map[string]string)
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go func(u string) {
defer wg.Done()
if result, err := fetcher(ctx, u); err == nil {
mu.Lock()
results[u] = result
mu.Unlock()
}
}(url)
}
wg.Wait()
return results
}