

请教各位一个问题,context 超时控制,需要控制任务超时处理。
这个真正在干活的任务如果耗时太长,导致达到超时时间,此时 context 发送 timeout 消息给 task 函数,
此时,task 函数退出了。可是这个真正干活的协程 还是会继续运行。
我如何能控制干活的携程也可以跟随 context 的信号退出呢?
是我理解有问题,还是例子不对呢?


请教各位一个问题,context 超时控制,需要控制任务超时处理。
这个真正在干活的任务如果耗时太长,导致达到超时时间,此时 context 发送 timeout 消息给 task 函数,
此时,task 函数退出了。可是这个真正干活的协程 还是会继续运行。
我如何能控制干活的携程也可以跟随 context 的信号退出呢?
是我理解有问题,还是例子不对呢?
1
linklinp Aug 2, 2019
把 ctx 再传入 go func 里不就可以
|
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.") } ``` 这个示例函数有帮助吗? |
3
useben Aug 2, 2019
1、主协程退出,其他子协程全都退出
2、想达到超时控制回收全部子协程。直接从顶层到底层一直传 context 就 ok 了 context 本来就是为了解决树形 goroutine 的同步和控制问题 |
4
reus Aug 3, 2019
你理解有问题,ctx 是给最里面那个 goroutine 用的,就是所有需要监听超时的,都需要 <-ctx.Done()
|