doupu3635
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
    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

    点赞 评论

相关推荐