CYSDL 3: Solution


This is the solution to the Can You Spot the DeadLock 3.

The problem

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.

Expected
Expected Result

The major failure here is the use of if(!condition) instead of while(!condition).
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.

Sample result
Sample result

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.