drnf09037160 2017-05-08 17:56
浏览 781
已采纳

当上下文变量超出golang的范围时,Context.Done()是否会解除阻止?

Will context.Done() unblock when a context variable goes out of scope and cancel is not explicitly called?

Let's say I have the following code:

func DoStuff() {
    ctx, _ := context.WithCancel(context.Background())
    go DoWork(ctx)
    return
}

Will ctx.Done() unblock in DoWork after the return in DoStuff()?

I found this thread, https://groups.google.com/forum/#!topic/golang-nuts/BbvTlaQwhjw, where the person asking how to use Context.Done() claims that context.Done() will unblock when the context variable leaves scope but no one validated this, and I didn't see anything in the docs.

  • 写回答

2条回答 默认 最新

  • dongtai6741 2017-05-08 18:12
    关注

    No, it doesn't cancel automatically when the context leaves scope. Typically one calls defer cancel() (using the callback from ctx.WithCancel()) oneself to make sure that the context is cancelled.

    https://blog.golang.org/context provides a good overview of how to use contexts correctly (including the defer pattern above). Also, the source code https://golang.org/src/context/context.go is quite readable and you can see there's no magic that would provide automatic cancellation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 elasticsearch
  • ¥30 python ttk 获取下拉框问题
  • ¥15 uniapp的uni-datetime-picker组件在ios端不适配
  • ¥15 前端 uniapp App端在离线状态如何使用modbus 连接手机蓝牙进行读写操控机器?
  • ¥15 SQL语句根据字段自动生成行
  • ¥500 “掌声响起来”软件(不确定性人工智能)
  • ¥500 我要找大模型一体机产品手册和应用案例
  • ¥20 关于游戏c++语言代码问题
  • ¥15 如何制作永久二维码,最好是微信也可以扫开的。(相关搜索:管理系统)
  • ¥15 delphi indy cookie 有效期