dongyirong3564 2017-04-16 07:41
浏览 20
已采纳

有没有更简洁的方法来创建在通道上接收后被取消的上下文?

I need to invoke a function that takes a Context as a parameter. This block of code has access to a channel that is used for signalling that the operation should be cancelled.

Here is what I am currently using to cancel the Context when a value is received:

func doSomething(stop <-chan bool) {
    ctx, cancel := context.WithCancel(context.Background())
    go func() {
        select {
        case <-ctx.Done():
        case <-stop:
            cancel()
        }
    }()
    longRunningFunction(ctx)
}

The intended control flow is as follows:

  • If the task runs to completion, it will cancel the context, the <-ctx.Done() will fire, and the goroutine will terminate.

  • If a value is received on stop, the context is cancelled, notifying the task that it should quit. Once again, the goroutine will terminate when this happens.

This seems overly complex. Is there a simpler way to accomplish the intended behavior?

  • 写回答

1条回答 默认 最新

  • doujiao3346 2017-04-16 13:50
    关注

    As @ain mentionned, your code currently leaks the goroutine if the longRunningFunction runs to the end and nothing is sent on stop (or it is not closed): the select statement will never be fulfilled (the only way for the context to be done is when something comes out of stop to call cancel).

    Here is a way to fix it (mainly an implementation of @ain's comment):

    func doSomething(stop <-chan bool) {
        ctx := context.TODO() // because in the future, you might pass a ctx arg to this function, from which you could then "inherit"
        ctx, cancel := context.WithCancel(ctx)
        defer cancel() // to be sure to release the associated resources whatever happens (and prevent the following goroutine from leaking)
        go func() {
            select {
            case <-ctx.Done():
            case <-stop:
                cancel()
            }
        }()
        longRunningFunction(ctx)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装