doupu3635 2019-09-03 11:54
浏览 10
已采纳

如何修复工作者池死锁

I wrote a pool of workers, where the job is to receive an integer and return that number converted to string. However I faced a fatal error: all goroutines are asleep - deadlock! error. What am I doing wrong and how can I fix it?

https://play.golang.org/p/U814C2rV5na

  • 写回答

1条回答 默认 最新

  • douqiandai4327 2019-09-03 12:10
    关注

    I was able to replicate your issue and fix it by using a pointer to master instead of a normal variable.

    Basically just change your NewWorker() method to this:

    func (m *Master) NewWorker() {
        m.Workers = append(m.Workers, Worker{})
    }
    

    Here's the output the program prints after the change:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    .
    .
    .
    

    Reason:

    Everytime you called NewWorker() method, you weren't appending a worker to the same master object. That's why the slice never got populated with 3 workers, as should've been the case.

    Go Playground

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

报告相同问题?

悬赏问题

  • ¥15 深度神经网络传递自变量损失
  • ¥15 oracle数据库备份表如何操作
  • ¥15 软件定义网络mininet和onos控制器问题
  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)