Algo-Sim › Concurrency
Print FooBar Alternately
Medium · Concurrency · step through it in Java, Python and C++ on your own input
Two threads take turns: foo, bar, foo, bar. Two semaphores act as a baton: each thread waits for its own permit and hands the other one over after printing.
Problem
One FooBar object is shared by two threads: one calls foo(), which prints "foo" n times, and the other calls bar(), which prints "bar" n times. Make the output alternate, "foobar" repeated n times, whichever thread the scheduler runs first. start names the thread that runs first; return the output.
Constraints
- 1 ≤ n ≤ 4 here (1000 on LeetCode)
- start is foo or bar
- No busy-waiting
Edge cases to test
- n = 1
- The bar thread starts first
- Large n (no busy waiting)
Follow-up questions
- Why semaphores instead of a shared flag?
- Spinning on a flag burns CPU and needs
volatile; a semaphore blocks the thread until its turn. - How do you extend it to three threads?
- Three semaphores in a ring, each thread releasing the next one’s permit (as in Print Zero Even Odd, LC 1116).
Solution
Java
import java.util.concurrent.Semaphore;
class FooBar {
private final int n;
private final Semaphore fooTurn = new Semaphore(1); // foo goes first
private final Semaphore barTurn = new Semaphore(0);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
fooTurn.acquire();
printFoo.run();
barTurn.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
barTurn.acquire();
printBar.run();
fooTurn.release();
}
}
}Python
import threading
class FooBar:
def __init__(self, n):
self.n = n
self.foo_turn = threading.Semaphore(1) # foo goes first
self.bar_turn = threading.Semaphore(0)
def foo(self, printFoo):
for _ in range(self.n):
self.foo_turn.acquire()
printFoo()
self.bar_turn.release()
def bar(self, printBar):
for _ in range(self.n):
self.bar_turn.acquire()
printBar()
self.foo_turn.release()C++
#include <bits/stdc++.h>
using namespace std;
// C++17 counting semaphore: a predicate handles spurious wakeups.
class Semaphore {
mutex m;
condition_variable ready;
int permits;
public:
explicit Semaphore(int n)
: permits(n) {}
void acquire() {
unique_lock<mutex> lock(m);
ready.wait(lock, [&] { return permits > 0; });
--permits;
}
void release() {
{
lock_guard<mutex> lock(m);
++permits;
}
ready.notify_one();
}
};
class FooBar {
int n;
Semaphore fooTurn{1}, barTurn{0};
public:
explicit FooBar(int n)
: n(n) {}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; ++i) {
fooTurn.acquire();
printFoo();
barTurn.release();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; ++i) {
barTurn.acquire();
printBar();
fooTurn.release();
}
}
};
More Concurrency problems
- Print in Order (Easy)
- Design Bounded Blocking Queue (Medium)
- Producer–Consumer with wait and notifyAll (Medium)
- Read–Write Lock (Medium)