Algo-Sim › Concurrency
Print in Order
Easy · Concurrency · step through it in Java, Python and C++ on your own input
Three threads call first(), second() and third() in any order; make the output always first, second, third. A shared counter, wait() and notifyAll() hold the later threads back.
Problem
One Foo object is shared by three threads: thread A calls first(), thread B second() and thread C third(). The threads may start in any order. Make sure second() prints only after first() has finished and third() only after second(). order lists which call starts first; return the printed output.
Constraints
- order is a permutation of [1, 2, 3]
- No busy-waiting: blocked threads must sleep
- The output is always "firstsecondthird"
Edge cases to test
- Threads started in reverse order
- A spurious wake-up (wait in a loop)
- The same thread scheduled twice in a row
Follow-up questions
- Why
whileand notifaroundwait()? - A thread can wake without its condition being true (spurious wake-ups, or notifyAll for another thread), so it must re-check.
- What simpler tools work?
- Two
CountDownLatches (or semaphores starting at 0): second waits on the first latch, third on the second.
Solution
Java
class Foo {
private int done = 0; // how many methods have finished
public synchronized void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
done = 1;
notifyAll();
}
public synchronized void second(Runnable printSecond) throws InterruptedException {
while (done < 1) wait();
printSecond.run();
done = 2;
notifyAll();
}
public synchronized void third(Runnable printThird) throws InterruptedException {
while (done < 2) wait();
printThird.run();
}
}Python
import threading
class Foo:
def __init__(self):
self.done = 0 # how many methods have finished
self.cond = threading.Condition()
def first(self, printFirst):
with self.cond:
printFirst()
self.done = 1
self.cond.notify_all()
def second(self, printSecond):
with self.cond:
while self.done < 1:
self.cond.wait()
printSecond()
self.done = 2
self.cond.notify_all()
def third(self, printThird):
with self.cond:
while self.done < 2:
self.cond.wait()
printThird()C++
#include <bits/stdc++.h>
using namespace std;
class Foo {
int done = 0;
mutex m;
condition_variable changed;
public:
void first(function<void()> printFirst) {
unique_lock<mutex> lock(m);
printFirst();
done = 1;
changed.notify_all();
}
void second(function<void()> printSecond) {
unique_lock<mutex> lock(m);
changed.wait(lock, [&] { return done >= 1; });
printSecond();
done = 2;
changed.notify_all();
}
void third(function<void()> printThird) {
unique_lock<mutex> lock(m);
changed.wait(lock, [&] { return done >= 2; });
printThird();
}
};
More Concurrency problems
- Print FooBar Alternately (Medium)
- Design Bounded Blocking Queue (Medium)
- Producer–Consumer with wait and notifyAll (Medium)
- Read–Write Lock (Medium)