Races and deadlocks
Two concurrency bugs account for most of the hard failures. A race is two threads using shared state without an order the program controls, and the previous lessons showed a forced one. A deadlock is two threads that each hold what the other needs and wait for ever. This lesson makes a deadlock visible with a timeout instead of hanging, and shows the shape that avoids it.
What a deadlock is
The program has one object, a thread that locks it and a second thread that wants it. The holder waits on an event that the main thread sets, so the main thread can measure the state of the lock without any race:
var gate = new object();
var ready = new ManualResetEventSlim();
var hold = new ManualResetEventSlim();
var holder = new Thread(() =>
{
lock (gate)
{
ready.Set();
hold.Wait();
}
});
holder.Start();
ready.Wait();
var first = Monitor.TryEnter(gate, 100);
Console.WriteLine($"first try {first}");
var second = Monitor.TryEnter(gate, TimeSpan.FromMilliseconds(100));
Console.WriteLine($"second try {second}");
if (second)
{
Monitor.Exit(gate);
}
hold.Set();
holder.Join();
var third = Monitor.TryEnter(gate, 100);
Console.WriteLine($"after release {third}");
if (third)
{
Monitor.Exit(gate);
}
dotnet run
first try False
second try False
after release True
Both attempts failed while the holder kept the lock, each after waiting a hundred milliseconds, and the third succeeded once the holder released it. A lock is Monitor.Enter without a timeout, so the same two attempts written with lock would have waited for ever. The rule for a program that must not hang is to use Monitor.TryEnter where a timeout is acceptable, and to log the failure with the two locks named.
Monitor.TryEnter and a timeout
- Monitor.TryEnter(obj) takes the lock only if it is free and returns at once.
- Monitor.TryEnter(obj, milliseconds) or a TimeSpan waits that long and returns false.
- Every successful attempt must be paired with Monitor.Exit in the same thread, which a try/finally guarantees.
- A lock held across a Console.WriteLine is held across a system call, and that is how a real deadlock grows: take the lock, copy the data out, release, then print.
Lock ordering
A deadlock between two locks is usually a program that takes them in different orders. Thread A takes first and then second, thread B takes second and then first, and if both get their first lock before either gets its second, both wait for ever. The fix is a total order that every thread follows: always the same object first, or one lock instead of two, or a SemaphoreSlim with a timeout. A program that cannot avoid two locks documents their order next to their declaration, because the next reader cannot see it from the call site.
A live lock is the sibling of a deadlock: both threads keep retrying and neither makes progress, which the output shows as a loop that never ends while the CPU is busy. A back-off, a queue or a lock removes it; adding a sleep hides it.
Lazy as a safe shared value
The safe way to share one initialisation is not a hand-written if (value is null). Lazy<T> creates the value once, even when eight tasks ask for it at the same time, and the factory below counts how often it ran:
var created = 0;
var lazy = new Lazy<object>(() =>
{
Interlocked.Increment(ref created);
return new object();
});
var tasks = Enumerable.Range(0, 8).Select(_ => Task.Run(() => lazy.Value)).ToArray();
await Task.WhenAll(tasks);
Console.WriteLine($"created {created}");
Console.WriteLine($"same {tasks.All(t => ReferenceEquals(t.Result, tasks[0].Result))}");
Console.WriteLine($"value {lazy.IsValueCreated}");
dotnet run
created 1
same True
value True
The factory ran once, all eight tasks received the same object, and the value is created afterwards. The default mode, ExecutionAndPublication, is the thread-safe one; a Lazy of an expensive value that is never read costs nothing, which is why it fits a configuration or a connection. The next lesson schedules work with timers.
Exercises
- Replace Monitor.TryEnter with Monitor.Enter and run the program with a timeout of ten seconds, then kill it.
- Write two threads that take two locks in opposite orders with TryEnter and print which one backs off.
- Read the eight results of the Lazy program and compare their references.
- Give the Lazy of the last program a factory that throws and read what the second task gets.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a deadlock?
Answer
Two threads each hold what the other needs and wait for ever
Neither can continue, because each waits for a lock the other holds.
-
What does Monitor.TryEnter(obj, 100) do when the lock is held?
Answer
Waits up to 100 milliseconds and returns false
The timed form is what turns a hang into a measurable answer.
-
What does this program print?
var gate = new object(); var ready = new ManualResetEventSlim(); var hold = new ManualResetEventSlim(); var holder = new Thread(() => { lock (gate) { ready.Set(); hold.Wait(); } }); holder.Start(); ready.Wait(); Console.WriteLine(Monitor.TryEnter(gate, 100)); hold.Set(); holder.Join();Answer
False
The holder keeps the lock, so the timed attempt gives up and returns false.
-
What is the usual fix for a deadlock between two locks?
Answer
A total order in which every thread takes them
A consistent order means the two threads can never hold one each.
-
What does this program print?
var gate = new object(); var ready = new ManualResetEventSlim(); var hold = new ManualResetEventSlim(); var holder = new Thread(() => { lock (gate) { ready.Set(); hold.Wait(); } }); holder.Start(); ready.Wait(); hold.Set(); holder.Join(); Console.WriteLine(Monitor.TryEnter(gate, 100));Answer
True
The holder released the lock, so the attempt succeeds.
-
What does Lazy<T> guarantee?
Answer
The value is created once, even under concurrent access
The measured factory ran once for eight tasks.
-
What does this program print?
var created = 0; var lazy = new Lazy<object>(() => { Interlocked.Increment(ref created); return new object(); }); var tasks = Enumerable.Range(0, 8).Select(_ => Task.Run(() => lazy.Value)).ToArray(); await Task.WhenAll(tasks); Console.WriteLine(created);Answer
1
The default Lazy mode creates the value once for all callers.
-
Is Lazy<T> thread-safe by default?
Answer
Yes, in ExecutionAndPublication mode
The default mode allows one thread to run the factory and the others to wait.
-
What does this program print?
var lazy = new Lazy<int>(() => 6 * 7); Console.WriteLine(lazy.Value);Answer
42
Reading Value runs the factory and returns its result.
-
What is a live lock?
Answer
Threads that keep retrying and never make progress
The CPU is busy and the state does not change, unlike a deadlock where the threads sleep.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev