Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a program that will surely go into deadlock [closed]

I recently got this questions asked in an interview.

I answered that deadlock occurs if the interleaving goes wrong, but the interviewer insisted that a program that will always go into deadlock regardless of interleaving can be written .

Can we write such a program ? Can you point me to some example program like that ?

like image 859
user2434 Avatar asked Jan 16 '12 12:01

user2434


People also ask

What is a deadlock in C?

A deadlock is a situation in which two computer programs sharing the same resource are effectively preventing each other from accessing the resource, resulting in both programs ceasing to function.

What is deadlock in oops with example?

Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.

How can we avoid deadlock in C?

One of the most common ways of avoiding a deadlock is to always lock the two mutexes in the same order. If we always lock mutex A before mutex B, then we'll never have a deadlock.


1 Answers

UPDATE: This question was the subject of my blog in January 2013. Thanks for the great question!


How can we write a program that will always go into deadlock no matter how the threads are scheduled?

Here's an example in C#. Note that the program appears to contain no locks and no shared data. It has only a single local variable and three statements, and yet it deadlocks with 100% certainty. One would be hard-pressed to come up with a simpler program that deadlocks with certainty.

Exercise to the reader #1: explain how this deadlocks. (An answer is in the comments.)

Exercise to the reader #2: demonstrate the same deadlock in Java. (An answer is here: https://stackoverflow.com/a/9286697/88656)

class MyClass {   static MyClass()    {     // Let's run the initialization on another thread!     var thread = new System.Threading.Thread(Initialize);     thread.Start();     thread.Join();   }    static void Initialize()    { /* TODO: Add initialization code */ }    static void Main()    { } } 
like image 146
Eric Lippert Avatar answered Sep 24 '22 12:09

Eric Lippert