Coordinate Two Threads to Print Odd and Even Numbers in Order
Last updated: November 29, 2026
Quick Overview
Start two threads, one responsible for odd numbers and one for even numbers, so that together they output 1 through n strictly in order.
0
0
0 solved
Start two threads, one responsible for odd numbers and one for even numbers, so that together they output 1 through n strictly in order.
A short Google phone screen warm-up that checks whether a candidate can use a condition variable correctly rather than sleeping or busy-waiting. The interviewer looks for a shared predicate, a while-loop wait, and clean termination for both threads.
What the Interviewer Expects
- Shares one counter protected by a lock
- Waits on a condition variable inside a while loop
- Notifies after changing state
- Ensures both threads exit, including the one waiting when the last number prints
- Avoids sleeps and busy loops
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- Generalize to k threads printing in round-robin order.
- How would you do it with two semaphores instead of a condition variable?
- Why is `notify_all` safer than `notify` here, and when could `notify` be enough?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
- Output is exactly
1, 2, ..., n. - Thread A emits only odd numbers, thread B only even numbers.
- Works for
n = 0andn = 1; both threads terminate....
High-Level Design
Shared state is next, the number due to be printed. Each thread waits until next has its parity or exceeds n. When its turn comes it emits, increments, and notifies. The wait predicate includes ...