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);
        }
    }
}

}

Answers


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


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.


Simple - you are running in a single thread.


Need Your Help

is_valid() vs clean() django forms

django forms validation

In the process of finding a way to validate my django forms, I came across two methods is_valid() and clean() in the django docs. Can anyone enlighten me the how they are different/same? What are the

Django - User full name as unicode

python django django-models django-users

I have many Models linked to User and I'd like my templates to always display his full_name if available. Is there a way to change the default User __unicode__() ? Or is there another way to do it ...