hoanganh17b
hoanganh17b

Reputation: 867

Reproduce threading deadlock with simple C#

I guess I got problems with deadlock...My program is working well but some time it get unresponsive...???. In source code (C#)..have no lock(objet) or ReaderWriterLockSlim... I did try to reproduce the deadlock with 2 threads using same object (List) but no success..

int n = 0;                      
  List<int> temp = new List<int>();
  var up = new Thread(() =>{
     for (int i = 0; i < 100000; i++){
     n++;
     temp.Add(i);                   
}
});

var down = new Thread(() => {
    for (int i = 0; i < 100000; i++){
        n--;
         try{
           temp.Remove(i);
         }catch {
           Console.WriteLine("No item {0} to remove", i);
         }
        }
});

up.Start();
down.Start();
down.Join();
up.Join();
Console.WriteLine(String.Join(",",temp));

The snipe code above still works without deadlock..??? Could someone help me to reproduce the deadlock with 2 threads using same variable without lock(object) or System lock...

Thank in Advance

Upvotes: 0

Views: 461

Answers (2)

Jeroen van Langen
Jeroen van Langen

Reputation: 22083

Normally a deadlock occurs when using locks or synchronization.

Most common deadlocks are updateing the Gui from a thread. Like:

Thread thread = new Thread( () => 
{ 
    Invoke(new Action(() => 
    {
        Label1.Text = "something";
    }));
});

thread.Start();

// this join will prevent the messageloop from running, but the invoke waits on the messageloop to execute it's action.
thread.Join();

But it isn't like your case.

I think you mean the n is increased and decreased (same as mutating the list) on different threads. This isn't a deadlock, but threadsafety problem.

Even if you put a lock into it, you don't get a deadlock there.

object lockObj = new object();

 var up = new Thread(() =>
 {
     for (int i = 0; i < 100000; i++)
     {
         lock(lockObj)
         {
             n++;
             temp.Add(i);                   
         }
     }
 });

 var down = new Thread(() => 
 {
     for (int i = 0; i < 100000; i++)
     {
         lock(lockObj)
         {
             n--;
             try
             {
                 temp.Remove(0);
             }
             catch 
             {
                 Console.WriteLine("No item {0} to remove", i);
             }
         }
     }
});

But this will slowdown the process very much.

Upvotes: 1

meilke
meilke

Reputation: 3280

List is not thread-safe so this will be the cause of your problem. You should create a thread-safe solution (using lock or with thread-safe collections) and not focus on recreating the deadlock. What will that tell you?

Upvotes: 3

Related Questions