Skip to the page

Operating systems · core

Race conditions, mutex and semaphore

When threads share data, the result can depend on timing. A mutex or a semaphore makes access safe.

The notes

What you must know

  • A race condition: the result depends on the order in which threads run. total += x is three steps (read, add, write), so two threads can lose an update.
  • The start order of threads is not the execution order. If a thread needs data from another, make it wait: join(), a semaphore, a condition variable or a CountDownLatch. A sleep is not a fix.
  • A mutex is a lock for one critical section. Only one thread holds it, and only that thread should unlock it (ownership).
  • A semaphore is a counter with two atomic operations: wait (P: decrement, block if it would go below zero) and signal (V: increment and wake a waiter). A counting semaphore allows up to N at once.
  • Example: 5 printers in a lab is a semaphore that starts at 5. One shared bank balance is a mutex.
  • A binary semaphore has no owner: any thread can signal it. That suits signalling between threads.
  • Producer and consumer: use two semaphores (empty slots and full slots) and a mutex for the buffer.
  • Order matters: wait on the semaphore first, then lock the mutex. If you lock the mutex first and then wait on a semaphore, you can deadlock: the consumer holds the mutex and waits for an item, and the producer cannot get the mutex to add one.

The red pen

Common traps: mistake → fix

  • Mistake: A mutex is a binary semaphore

    Fix: a mutex has an owner; a semaphore does not.

  • Mistake: A semaphore allows only one thread

    Fix: a counting semaphore allows N.

  • Mistake: volatile fixes total += x

    Fix: it is still read, add, write.

  • Mistake: Add a sleep before the average is calculated

    Fix: it only hides the ordering bug.

Easy to hard

Questions interviewers ask, easy to hard

  1. Mutex or semaphore: what is the difference?
  2. Two threads read marks and calculate the average. It sometimes prints 0. Why?
  3. Spot the bug in a producer that locks the mutex and then waits on a semaphore.
  4. What is a critical section?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview