Deadlock

Posted on May 31, 2007 @ 02:20 books csharp school

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    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…

1
2
3
4
5
6
7
8
9
10
11
12
    lock ( _resourceB ) {
        
    }
    
    // translates too
    Monitor.Enter( _resourceB);
    try {
        
    }
    finally {
        Monitor.Exit( _resourceB );
    }

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

1
2
3
4
5
6
7
8
9
    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)