dongshuan8722 2019-01-23 21:26
浏览 111
已采纳

上下文包与完成的通道,避免goroutine泄漏

There are two different approaches to clean up a goroutine.

  1. Use a kill channel to signal cancellation and a done channel to indicate that goroutine has been terminated.

    type Worker struct {
      Done chan struct{}
      Kill chan struct{}
      Jobs chan Job
    }
    
    func (w *Worker) Run() {
      defer func() {
        w.Done <- struct{}{}
      }
      for {
        select {
        case <-w.Kill:
          return
        case j := <-w.Jobs:
          // Do some work
      }
    }
    
    go w.Run()
    w.Kill <- struct{}{}
    
  2. Use context to cancel

    type Worker struct {
      Ctx context.Context
      Cancel context.CancelFunc
      Jobs chan Job
    }
    
    func (w *Worker) Run() {
      for {
        select {
        case <-w.Ctx.Done():
          return
        case j := <-w.Jobs:
          // Do some work
      }
    }
    
    go w.Run()
    w.Cancel()
    

What are the pros/cons of each approach? Which one should I default to?

I understand that if I want to kill a tree of interconnected goroutines, I should go with context approach but let's just say I have a simple worker that doesn't start other goroutines internally.

  • 写回答

1条回答 默认 最新

  • dongwen5336 2019-01-23 21:52
    关注

    Go 1.7 Release Notes

    Context

    Go 1.7 moves the golang.org/x/net/context package into the standard library as context. This allows the use of contexts for cancelation, timeouts, and passing request-scoped data in other standard library packages, including net, net/http, and os/exec, as noted below.

    For more information about contexts, see the package documentation and the Go blog post “Go Concurrent Patterns: Context.”


    There were problems. The context package was introduced to solve them.

    Now that you have read all of the relevant documentation, What is your question?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c