-1

Can someone PLEASE show me a simple deadlock with two threads EXAMPLE in C++

The_Marcerie
  • 29
  • 1
  • 1

1 Answers1

6

One of the simplest ones - it's pseudo code but you should be able to translate that into pretty much any language:

Thread 1:

 acquire_lock(lockA);
   ... do some work ...
 acquire_lock(lockB);

Thread 2:

acquire_lock(lockB);
  ... do some other work ...
acquire_lock(lockA);

If thread one is executing and isn't holding lockB yet and thread two acquires lockB, neither of the threads can continure past the second lock acquisition.

Timo Geusch
  • 24,095
  • 5
  • 52
  • 70
  • is there a way that a deadlock happens with only one lock + IO operation? – Bionix1441 Feb 23 '18 at 14:30
  • Not to the best of my knowledge. The standard deadlock scenario pretty much requires two locks. That said, if one thread does blocking IO and holds the lock for the length of the IO, another thread will not be able to get the lock during that time and thus the symptoms will be very close to those of a "real" deadlock. The difference being that one of them will eventually resolve itself and the other won't. – Timo Geusch Mar 18 '18 at 18:44