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 c++ word自动化,为什么可用接口是空的?
    • ¥15 Matlab计算100000*100000的矩阵运算问题:
    • ¥50 VB6.0如何识别粘连的不规则的数字图片验证码
    • ¥16 需要完整的这份订单所有的代码,可以加钱
    • ¥30 写一个带界面控制的机房电脑一键开机关机并且实时监控的软件
    • ¥15 Stata数据分析请教
    • ¥15 请教如何为VS2022搭建 Debug|win32的openCV环境?
    • ¥15 关于#c++#的问题:c++如何使用websocketpp实现websocket接口调用,求示例代码和相关资料
    • ¥15 51单片机的外部中断,按下按键后不能切换到另一个模式