IntermediateTopic 43 of 104Software & Computing

Race conditions and deadlocks

Bugs from unsynchronised access and cyclic lock waiting.

In depth

A race condition occurs when outcomes depend on unsynchronised timing of threads accessing shared data. Deadlock arises when threads wait for each other's locks in a cycle. Avoid with consistent lock ordering, timeouts, minimal shared state, immutable data and message passing.

Key points

  • Four Coffman conditions
  • Livelock and starvation
  • Thread sanitisers
Example

Two threads incrementing a counter without a lock can lose updates.

Why it matters

Race conditions and deadlocks are among the hardest bugs to find, so knowing their causes helps you prevent them.

Where this is used

  • Two threads updating a bank balance and losing one update.
  • Two tasks each waiting for a lock the other holds.
  • Writing a counter from several threads without synchronisation.

Frequently asked questions

What is Race conditions and deadlocks?

Bugs from unsynchronised access and cyclic lock waiting.

Why is it important to understand race conditions and deadlocks?

Race conditions and deadlocks are among the hardest bugs to find, so knowing their causes helps you prevent them.

What is a race condition?

A bug where the result depends on the timing of threads accessing shared data without proper coordination.

How do you avoid deadlock?

Acquire locks in a consistent order, keep critical sections short, and use timeouts or lock-free designs where appropriate.

How is Race conditions and deadlocks used in practice?

Typical applications include two threads updating a bank balance and losing one update, two tasks each waiting for a lock the other holds and writing a counter from several threads without synchronisation.

What should I learn before Race conditions and deadlocks?

Study "Concurrency and threads" first (topic 42 of 104 in Software & Computing). It covers the groundwork this topic builds on.

What are the key points of Race conditions and deadlocks?

Four Coffman conditions. Livelock and starvation. Thread sanitisers.

Can you give an example of Race conditions and deadlocks?

Two threads incrementing a counter without a lock can lose updates.

What comes after Race conditions and deadlocks?

The next topic is "Asynchronous programming", which builds directly on this one.

How difficult is Race conditions and deadlocks?

It is classed as Intermediate in Software & Computing (topic 43 of 104). It is an intermediate topic. Work through the beginner topics in Software & Computing first.

Learning path

Want to practise? Open the interactive course for quick checks, quizzes, simulations and progress tracking.

Related topics