CYSDL 1: Solution

As promised, here is the answer to my question
Here the deadlock manifests itself as the main thread stuck on one of the Thread.Join calls and the associated thread’s (_firstRunner or _secondRunner) Monitor.Wait(_synchro) call.

The problem lies with the Monitor.Pulse(_synchro) call, because it wakes only one thread waiting allowing it to end properly. The other thread is still waiting for a signal that will never happen. And ultimately, the main thread is waiting for both threads to end, and we already know that it will not happen.

How to fix: you need to replace Monitor.Pulse(_synchro) by Monitor.PulseAll(_synchro).

This example reminds us that deadlocks do not systematicaly occurs on lock statement and that one must be careful regarding thread termination. Plus, here the problem does not relate to the classical ordering of resource acquisition.

The only random aspect was which of the two runner threads would be locked.

It also raises concern about when and why someone has to worry about using Pulse or PulseAll.

How can it be improved: there is a call to Thread.Sleep that I did place just to make sure that both runner thread where waiting for the signal. This is never the proper way to make a rendez-vous point between threads. But this is neither a trivial matter and adequate rendez-vous code would add a significant chunck of code.

Rendez-vous will probably a topic for another exercise.

How did you fare in this exercise

PS: This an automated post

3 thoughts on “CYSDL 1: Solution

Leave a Reply

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

You are commenting using your 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.