V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
nigulasida

请教一个 context 同步问题

  •  
  •   nigulasida · Aug 2, 2019 · 2524 views
    This topic created in 2470 days ago, the information mentioned may be changed or developed.

    ewjIBQ.png

    ewv3gf.png

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

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

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

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

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

    4 replies    2019-08-03 13:42:38 +08:00
    linklinp
        1
    linklinp  
       Aug 2, 2019
    把 ctx 再传入 go func 里不就可以
    jessun1990
        2
    jessun1990  
       Aug 2, 2019
    ```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  
       Aug 2, 2019
    1、主协程退出,其他子协程全都退出
    2、想达到超时控制回收全部子协程。直接从顶层到底层一直传 context 就 ok 了

    context 本来就是为了解决树形 goroutine 的同步和控制问题
    reus
        4
    reus  
       Aug 3, 2019
    你理解有问题,ctx 是给最里面那个 goroutine 用的,就是所有需要监听超时的,都需要 <-ctx.Done()
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5595 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 59ms · UTC 07:31 · PVG 15:31 · LAX 00:31 · JFK 03:31
    ♥ Do have faith in what you're doing.