go – How to fix Worker Pool Deadlock-ThrowExceptions

Exception or error:

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

How to solve:

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

Leave a Reply

Your email address will not be published. Required fields are marked *