Wrongful expectations - deadlocks
A deadlock is described pretty succinctly by its name already. It occurs when two or more processes attempt to gain access to a resource which the other is holding, while that other thread is simultaneously waiting to gain access to a resource which it is holding.
For example:
- Thread 1 gains access to resource A
- Thread 1 and 2 both want to gain access to resource B
- Thread 2 wins and now owns B, with thread 1 still waiting on B
- Thread 2 wants to use A now, and waits for access
- Both thread 1 and 2 wait forever for a resource
In this situation, we assume that the thread will be able to gain access to each resource at some point, while the opposite is true, thanks to each thread holding on to the resource which the other thread needs.
Visualized, this deadlock process would look like this:
This makes it clear that two basic rules when it comes to preventing deadlocks are:
- Try to never hold more than one lock at any time.
- Release any held locks as soon as you can.
We saw...