Can you spot the Deadlock 4: the solution!

Can you spot the Deadlock 4: the solution!

As most of you correctly highlighted, the last exercise exhibits a deadlock situation. The main thread here simply creates and starts another thread and waits for its completion, but this expectation is never fulfilled.

class Program
  static void Main(string[] args)
    var workerThread = new Thread(Worker);

When one looks at the worker thread code, you realize that the stopping condition is never going to be met: Thread.CurrentThread.IsAlive just cannot be false! The current thread is alive, otherwise it will be dead, hence not executing code.

  static void Worker()
    while (Thread.CurrentThread.IsAlive)

Based on a true story, this example shows a very common misconception, that the framework provides facilities to control the life cycle of threads, and for that matter that Join will trigger a graceful stop. Well, sorry to break this to you guys, this is just not happening. It is your responsibility to implement an appropriate mechanism.

Here is a valid implementation using a shared flag:

    public class Solution
        private readonly object synchro = new object();
        private bool run;

        static void Main(string[] args) {
            var workerThread = new Thread(Worker);
            run = true;
            lock (this.synchro) {
                run = false;
            // wait for the thread to start

        private void Worker() {
            for (;;) {
                lock (this.synchro) {
                    if (!run) {
                Console.Write("Blah ");

New! Available on GitHub: for the curious, the critics and the laziest, I have but the code on GitHub as a VS 2012 solution.

CYSDL: reboot, your opinion count. Vote!

For those who wonder why there has been no new CYSDL recently, let just say that I have been busy working on the amazing-I-can’t-believe-you’re-not-using-yet assertion library nFluent. But another important factor was I realized that CYSDL quizz needed larger code that may not fit well for the blog format.

For those who may not know Can You Spot The Deadlock, here are some explanations.

As I want to reboot the concept, please answer the following poll.


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 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.

Can You Spot the Deadlock 3?

Hello dear readers and coders

Welcome to the third ‘Can You Spot the Deadlock?’ trivia. Today’s exercise is still dedicated to the Monitor Pattern. Next one will explore other horizons.

As usual the code is in C#, it does compile but it will not run as is.


  • What is the issue here?
  • Where does it occur?
  • Can you fix it ? if yes how, if not, why

And please share your ideas through the comment!

using System;
using System.Threading;

namespace SpotTheDeadLock
  internal class SpotTheDeadlock3
    readonly object _synchro = new object(); // lock object

    public int _x = 1; // resulting data

    bool _mustStop;
    int _iteration = 0;
    int []_factor={2,3,5};

    // first running thread

    public void Runner1(int stepId) {
      while (true) {
        lock (_synchro) {
          if (_iteration % 3 != stepId && !_mustStop)

          if (_mustStop)

          _x = _x * _factor[stepId];

        } // _synchro
      } // while

  private void NextStep() {
    if (_iteration == 8)
      _mustStop = true;

  public static void Runner() {

    SpotTheDeadlock3 agent = new SpotTheDeadlock3();
    Thread thread1 = new Thread(() => agent.Runner1(0));
    Thread thread2 = new Thread(() => agent.Runner1(1));
    Thread thread3 = new Thread(() => agent.Runner1(2));



    if (agent._x != 2 * 2 * 2 * 3 * 3 * 3 * 5 * 5 * 5)
      throw new ApplicationException("Invalid result");

  } // class
} // namespace

Quizz time is closed, solution is available here

CYSDL 2: Solution

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

The problem

This code can deadlock. It actually deadlocks pretty fast on my testbed. The deadlock occurs between the notification mechanism and the unsubscription method in the client class!

Where does it occur?

The notification thread is locked trying to gets its notification through

public class Client: IDisposable {
private void OnEvent(object sender, EventArgs arguments) {
lock (this) // notification thread is locked here

The main thread is locked trying to unsubscribe properly
public class EventSource {
public event EventHandler EventOccured{
remove {
lock (this) // main thread is locked here

The source of the issue is that we have two conflicting resource acquisition paths:
1) The notification path, where first (the lock for) the event is acquired (to prevent modification on the fly of the subscribers list) and then the client (lock) is acquired (to ensure exclusive access to its internals).
2) The unsubscription path wich first acquire the client (to ensure exclusive access to its internals) and then acquire the event for safe unsubscription.

How can it be fixed?

That is the impossible part. There is no proper solution to this problem! That one of the reason I like it so much. But the keyword here is proper. You can resolve the deadlock assuming you are ok to relax the contract a bit.

What is the contract here?

This code (unsuccessful) implements a strong contract: The Client will not receive any notification before the end of the subscription method and it will not receive any notifications after the end of unsubscription method. The first assumption is in fact trivial: how could a client receive notifications from a source it has not subscribed to yet :-). The second one looks similar and quite harmless, it even looks like very desirable. But its a trap: every implementation of this contract offers deadlock opportunities!

You need to relax it a bit and remove the second requirement: you must accept to (potentialy) receive notifications even after a succesful unsubscription. Then you can drop the locks in EventSource.