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.

So:

  • 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)
            Monitor.Wait(_synchro);

          if (_mustStop)
            return;

          _x = _x * _factor[stepId];
          NextStep();

        } // _synchro
      } // while
    }

  private void NextStep() {
    if (_iteration == 8)
      _mustStop = true;
    else
      _iteration++;
    Monitor.PulseAll(_synchro);
  }

  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));

    thread1.Start();
    thread2.Start();
    thread3.Start();

    thread1.Join();
    thread2.Join();
    thread3.Join();

    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

One thought on “Can You Spot the Deadlock 3?

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 )

Twitter picture

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