初级会员
  • 第 8462 位会员
  • nfwater
  • 2017-05-23 17:22:28
  • Offline
  • 26 82

最近发布的文章

最近分享的资源

最近发布的项目

    暂无

最近的评论

  • 2020-12-14 00:19:36 评论了主题 请教 context.WithTimeout 的正确用法
    #2 @colinrs 有个问题:如果 watch 在超时时间 3s 内执行完,主协程仍要最低等待 3s,如何进一步优化?
  • 2020-12-14 00:13:56 评论了主题 请教 context.WithTimeout 的正确用法
    更正
  • 2020-12-14 00:03:19 评论了主题 请教 context.WithTimeout 的正确用法
    更正
  • 2020-11-29 17:19:21 评论了主题 请教 context.WithTimeout 的正确用法
    这样是可以的,但感觉不像是标准用法 ``` package main import ( "context" "fmt" "sync" "time" ) var wg sync.WaitGroup // main 设置一个 3s 超时的 ctx,传给每个 goroutine 第一个参数,每个 goroutine 又发起协程处理任务, // 假设需要 5s,通过监听 ctx.Done 判断是否超时退出 func main() { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() wg.Add(2) go watch(ctx, 1) go watch(ctx, 2) wg.Wait() fmt.Println("finished") } func watch(ctx context.Context, flag int) { defer wg.Done() go func() { fmt.Printf("doing something flag:%d\n", flag) time.Sleep(50 * time.Second) fmt.Println("finished flag:", flag) }() select { case <-ctx.Done(): fmt.Printf("watch %d %s\n", flag, ctx.Err()) return } } ```
  • up,也想问这个问题,还有更多回答吗