Multi-Threaded Coding
Coding problems where several threads must take turns, share data safely or wait for each other: locks, semaphores, condition variables and barriers, and how to pick one.
Overview
What these problems test
A multi-threaded coding problem gives you two or more threads that run at the same time and interleave in any order. Your job is to make the result correct no matter how they interleave, without stopping them from running in parallel where they can. The goal is three things: no race (two threads change shared data at once), no deadlock (threads wait for each other forever), and the required order of events.
Almost every problem is one of four coordination patterns. Name the pattern first; the primitive follows from it. For each pattern there is a simplest primitive that solves it.
- Ordering: B must run after A. Use a semaphore starting at 0; A releases it and B acquires it.
- Mutual exclusion: only one thread may be in a section at a time. Use a lock (mutex).
- Producer and consumer: threads pass items through a buffer. Use a condition variable, or a blocking queue.
- Resource allocation: each thread needs several locks. Use lock ordering, or a limit on who may try.
Match the problem to a pattern before you write code. Each primitive named here is described next.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio