Synchronize Two Threads So foo and bar Print in Strict Alternation
Quick Overview
Two threads share an object: one prints foo n times and the other prints bar n times. Add synchronization so the output is always foobar repeated n times under any scheduling. Tests thread coordination primitives, blocking rather than spinning, and an argument that rules out deadlock and missed signals.
Synchronize Two Threads So foo and bar Print in Strict Alternation
Company: Nutanix
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
A shared object has two methods: `foo` prints `foo` n times and `bar` prints `bar` n times.
```python
class FooBar:
def __init__(self, n: int):
self.n = n
def foo(self) -> None:
for _ in range(self.n):
print("foo", end="")
def bar(self) -> None:
for _ in range(self.n):
print("bar", end="")
```
Two threads share one `FooBar` instance: one thread calls `foo()` and the other calls `bar()`. Either thread may start first, and the scheduler may interleave them in any way. Add synchronization so that the output is always `foobar` repeated n times, for example `foobarfoobar` when n is 2. Write the code in a language of your choice and explain why it is correct.
```hint Whose turn is it
Think about what each thread must wait for before it prints, and which thread should end that wait.
```
### Constraints and Clarifications
- `n` is a positive integer, and both methods use the same `n`.
- Each method is called exactly once, each by its own thread.
- The printing stays inside `foo` and `bar`; only the coordination between the threads is missing.
### Clarifying Questions
- Which synchronization primitives may be used: semaphores, a mutex with condition variables, atomics?
- May a waiting thread spin in a loop, or must it block until it is its turn?
- Is the object used for a single run, or must it support running the two methods again afterwards?
- Should the design extend to more than two threads printing in a fixed rotation?
### What a Strong Answer Covers
- A shared turn state or signaling primitive that forces `foo` before `bar` in every round, whichever thread starts first
- Blocking waits rather than spinning, with the condition re-checked after every wakeup when a condition variable is used
- An argument that the output is correct for every interleaving and that neither thread can deadlock or miss a signal
- Correct placement of the print relative to the handoff between threads
- Working code, with the chosen primitive weighed against at least one alternative
### Follow-up Questions
- Generalize the solution to k threads that must print in a fixed round-robin order.
- What happens with your solution if the `bar` thread starts long before the `foo` thread?
- Implement it with only a mutex and a condition variable. Why must the wait sit inside a loop?
- One thread throws an exception partway through. What happens to the other thread, and how would you make the failure clean?
Overview: Two threads share an object: one prints foo n times and the other prints bar n times. Add synchronization so the output is always foobar repeated n times under any scheduling. Tests thread coordination primitives, blocking rather than spinning, and an argument that rules out deadlock and missed signals.
A shared object has two methods: foo prints foo n times and bar prints bar n times.
class FooBar:
def __init__(self, n: int):
self.n = n
def foo(self) -> None:
for _ in range(self.n):
print("foo", end="")
def bar(self) -> None:
for _ in range(self.n):
print("bar", end="")
Two threads share one FooBar instance: one thread calls foo() and the other calls bar(). Either thread may start first, and the scheduler may interleave them in any way. Add synchronization so that the output is always foobar repeated n times, for example foobarfoobar when n is 2. Write the code in a language of your choice and explain why it is correct.
Constraints and Clarifications
n
is a positive integer, and both methods use the same
n
.
Each method is called exactly once, each by its own thread.
The printing stays inside
foo
and
bar
; only the coordination between the threads is missing.
Clarifying Questions Guidance
Which synchronization primitives may be used: semaphores, a mutex with condition variables, atomics?
May a waiting thread spin in a loop, or must it block until it is its turn?
Is the object used for a single run, or must it support running the two methods again afterwards?
Should the design extend to more than two threads printing in a fixed rotation?
What a Strong Answer Covers Guidance
A shared turn state or signaling primitive that forces
foo
before
bar
in every round, whichever thread starts first
Blocking waits rather than spinning, with the condition re-checked after every wakeup when a condition variable is used
An argument that the output is correct for every interleaving and that neither thread can deadlock or miss a signal
Correct placement of the print relative to the handoff between threads
Working code, with the chosen primitive weighed against at least one alternative
Follow-up Questions Guidance
Generalize the solution to k threads that must print in a fixed round-robin order.
What happens with your solution if the
bar
thread starts long before the
foo
thread?
Implement it with only a mutex and a condition variable. Why must the wait sit inside a loop?
One thread throws an exception partway through. What happens to the other thread, and how would you make the failure clean?