c2cedge
CS Fundamentals · A — Operating Systems

Synchronization & Deadlocks

When threads share data they can corrupt it or freeze each other. Race conditions, locks and deadlocks are guaranteed interview ground.

Test weight: Very highAsked by: TCS, Infosys, product cosDifficulty: Medium–Hard

When multiple threads access shared data and at least one writes, the result can depend on timing — a race condition. The section of code that touches shared data is the critical section, and the OS provides synchronization tools (mutexes, semaphores) to ensure only one thread is inside it at a time.

Critical section & mutual exclusion

A race condition is when the outcome depends on the unpredictable order of thread execution. The fix is mutual exclusion: protect the critical section so only one thread enters at a time, using a lock (mutex) or a semaphore.

Mutex vs semaphore

ToolWhat it is
Mutexa lock owned by one thread; only the owner unlocks it
Binary semaphorea 0/1 signal; any thread can signal
Counting semaphoreallows up to N threads (N resources)

Deadlock: the four Coffman conditions

  • Mutual exclusion — a resource is held by one process at a time.
  • Hold and wait — a process holds one resource while waiting for another.
  • No preemption — resources can't be forcibly taken away.
  • Circular wait — a cycle of processes each waiting on the next.
⚡ The edge
  • All four Coffman conditions must hold for a deadlock — break any one to prevent it (e.g. a global lock ordering kills circular wait).
  • Mutex = ownership (lock/unlock by the same thread); semaphore = a counter/signal any thread can change. Use a mutex for mutual exclusion, a counting semaphore to limit access to N resources.
Worked example
'What is a race condition and how do you prevent it?'
  1. Define it: two or more threads access shared data concurrently and the result depends on timing.
  2. Identify the critical section — the code touching the shared data.
  3. Prevent it with mutual exclusion: a mutex or semaphore so only one thread is in the critical section at a time.
Worked example
'How can you prevent deadlock?'
  1. Recall the four conditions: mutual exclusion, hold-and-wait, no preemption, circular wait — all must hold.
  2. Breaking any one prevents deadlock.
  3. The most practical is breaking circular wait by acquiring locks in a fixed global order.
⚠ Watch out
  • A deadlock needs all four conditions — prevention means breaking just one.
  • Don't confuse deadlock (stuck forever) with starvation (keeps losing out) or a livelock (active but no progress).
  • A mutex must be unlocked by the same thread that locked it; a semaphore has no such ownership.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms