Luna Tech

Tutorials For Dummies.

Deadlock

2022-02-20


0. What is deadlock?

Multiple threads are competing shared resource but cannot get it unless it releases its own locked resource first.


1. Example

t1 is waiting for t2 to complete and release lock2; t2 is waiting for t1 to complete and release lock1; deadlock happens!

async Task Main()
{
	var stopwatch = new Stopwatch();
	stopwatch.Start();
	
	var t1 = Task.Run(() => {
		lock(lock1) {
			Thread.Sleep(1);
			lock(lock2){
				Console.WriteLine("Hello");
			}
		}
	});
	
	var t2 = Task.Run(() => {
		lock(lock2) {
			Thread.Sleep(1);
			lock(lock1) {
				Console.WriteLine("World");
			}
		}
	});
	
	await Task.WhenAll(t1, t2);
	
	Console.WriteLine($"It took: {stopwatch.ElapsedMilliseconds}ms to run");
}

static object syncRoot = new object();
static object lock1 = new object();
static object lock2 = new object();

2. How to avoid a deadlock?

Note: sometimes when you are consuming a third-party method inside your lock, it might cause a deadlock.