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 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器