V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
nigulasida
V2EX  ›  Go 编程语言

请教一个 context 同步问题

  •  
  •   nigulasida · 2019-08-02 16:43:32 +08:00 · 2150 次点击
    这是一个创建于 1736 天前的主题,其中的信息可能已经有所发展或是发生改变。

    ewjIBQ.png

    ewv3gf.png

    请教各位一个问题,context 超时控制,需要控制任务超时处理。

    这个真正在干活的任务如果耗时太长,导致达到超时时间,此时 context 发送 timeout 消息给 task 函数,

    此时,task 函数退出了。可是这个真正干活的协程 还是会继续运行。

    我如何能控制干活的携程也可以跟随 context 的信号退出呢?

    是我理解有问题,还是例子不对呢?

    4 条回复    2019-08-03 13:42:38 +08:00
    linklinp
        1
    linklinp  
       2019-08-02 17:20:10 +08:00
    把 ctx 再传入 go func 里不就可以
    jessun1990
        2
    jessun1990  
       2019-08-02 17:39:45 +08:00
    ```go
    // goroutineExample2 使用 done 信号来通知 goroutine 退出
    // channel 上接收 goroutine。
    func goroutineExample2() {
    doWork := func(
    done <-chan interface{}, strings <-chan interface{},
    ) <-chan interface{} {
    terminated := make(chan interface{})
    go func() {
    defer fmt.Println("doWork exited.")
    defer close(terminated)
    for {
    select {
    case s := <-strings:
    fmt.Println(s)
    case <-done:
    return
    }
    }
    }()
    return terminated
    }

    done := make(chan interface{})
    terminated := doWork(done, nil)

    go func() {
    fmt.Println("Canceling doWork goroutine ...")
    time.Sleep(10 * time.Second)
    close(done)
    }()
    <-terminated
    fmt.Println("Done.")
    }

    ```

    这个示例函数有帮助吗?
    useben
        3
    useben  
       2019-08-02 22:44:15 +08:00
    1、主协程退出,其他子协程全都退出
    2、想达到超时控制回收全部子协程。直接从顶层到底层一直传 context 就 ok 了

    context 本来就是为了解决树形 goroutine 的同步和控制问题
    reus
        4
    reus  
       2019-08-03 13:42:38 +08:00
    你理解有问题,ctx 是给最里面那个 goroutine 用的,就是所有需要监听超时的,都需要 <-ctx.Done()
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2276 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:26 · PVG 23:26 · LAX 08:26 · JFK 11:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.