31 May 2007

Deadlock

by mo


A deadlock occurs when two or more threads are trying to access the same data but are blocking each other from getting at the resources necessary to continue.

internal class Program 
{
  private static void Main() {
    Deadlocker deadlock = new Deadlocker();

    Thread first = new Thread(new ThreadStart(deadlock.First));
    Thread second = new Thread(new ThreadStart(deadlock.Second));
    first.Start();
    second.Start();

    first.Join();
    second.Join();
  }
}

/// <summary>
/// 1. First thread starts and locks resourceA
/// 2. Second thread starts and locks resourceB
/// 3. First thread blocks waiting for resourceB to be freed.
/// 4. Second thread blocks waiting for resourceA to be freed.
/// 5. The application stops in it's tracks.
/// </summary>
internal class Deadlocker {
  public void First() {
    lock (_resourceA) {
      lock ( (_resourceB) ) {
        Console.WriteLine("First");
      }
    }
  }

  public void Second( ) {
    lock ( _resourceB ) {
      lock ( ( _resourceA ) ) {
        Console.WriteLine( "Second" );
      }
    }
  }

  private object _resourceA = new object( );
  private object _resourceB = new object( );
}

Remember that lock implicitly translates too…

lock (_resourceB) {
    
}

// translates too
Monitor.Enter(_resourceB);
try {
    
}
finally {
  Monitor.Exit(_resourceB);
}

Instead of using Monitor.Enter(), you can use Monitor.TryEnter();

  if (!Monitor.TryEnter(_resourceB, TimeSpan.FromSeconds(5))) {
    throw new TimeoutException();
  }
  try {
      
  }
  finally {
    Monitor.Exit(_resourceB);
  }

For more info check out…

MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0 Application Development Foundation by Tony Northrup, Shawn Wildermuth, Bill Ryan

Read more about this title…

Assignment11.zip (9.12 KB)

books csharp