Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come this code does not deadlock?

Shouldn't the Log method block?

namespace Sandbox {
class Program {
    static void Main(string[] args) {
        var log = new Logger();
        lock (log) {
            log.Log("Hello World!");
        }
    }
}

public class Logger {
    public void Log(string message) {
        lock (this) {
            Console.WriteLine(message);
        }
    }
}

}

like image 872
Marco Avatar asked Feb 18 '11 19:02

Marco


People also ask

What is code deadlock?

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.


2 Answers

The same thread is acquiring the same lock twice. This works because .NET supports so-called recursive locks (aka reentrant mutexes).

like image 123
Konrad Rudolph Avatar answered Oct 04 '22 11:10

Konrad Rudolph


If a resource is locked by a thread, that thread is allowed in, even if it already owns a lock on it. The same is true for this

Object obj = new Object();

lock(obj) {
    lock(obj) {
        foo();
    }
}

Would lock out if you couldn't get through by virtue of being the same thread.

like image 42
corsiKa Avatar answered Oct 04 '22 12:10

corsiKa