This is the solution to the Can You Spot the DeadLock 3.
No deadlock today, this code does not produce the expected result (27000) with certainty. So it raises an explicit exception, most of the time.
why does it occur?
As you have probably guessed, the general intent is to have three agents, each of them responsible for applying a factor (2,3,5) in a sequential way. Sequence is orchestrated thanks to a step counter and the use of modulo so that each agent acts on the appropriate steps.
The major failure here is the use of
if(!condition) instead of
Improper use of the monitor pattern: agents assume that if they are woken up, it means their condition is fulfilled, which is clearly not the case: they are waken for each forward steps. Afterward, it’s a race condition between threads to get the lock.
As you can see, neither order nor execution count is secured. This code fails in many ways.
how to fix?
You just need to replace the ‘if(!condition)’ with ‘while(!condition)’ and bang, you’re done.
Actually, writing this code was harder than anticipated. My original plan was to use Pulse instead of PulseAll as I feared that PulseAll was giving too much away. But it turns out that all my attempts led to non working code or too obvious problems.
Feel free to submit your own if you want.
And see you for the next exercise.
One thought on “CYSDL 3: Solution”