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);
}
}
}
}
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With