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 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持