AlgoViz

Concurrency in an LLD round

medium 40 min

Sooner or later the interviewer asks what happens when two users do it at the same time.

Watch lesson5:07

The rink with three guards

Read it, run it, change a line and run it again.

Loading editor…

One thread is enough to see every answer. The test with forty threads is in the code walk on the Overview; run it on your own machine.

The same in Java
/** Correctness. onIce is guarded by "this". Rule: onIce <= places. */final class Gate {    private final int places;    private int onIce = 0;    Gate(int places) { this.places = places; }    synchronized boolean enter() {        if (onIce >= places) return false;        onIce++;        return true;    }    synchronized void leave() {        if (onIce == 0) throw new IllegalStateException("nobody is on the ice");        onIce--;    }}/** Coordination. The sharpener hands over, the desk waits. */final class Bench {    private final BlockingQueue<String> ready = new ArrayBlockingQueue<>(20);    void putReady(String pair) throws InterruptedException { ready.put(pair); }    /** null when nothing came in time. */    String takeReady(long millis) throws InterruptedException {        return ready.poll(millis, TimeUnit.MILLISECONDS);    }}/** Scarcity. As many permits as pairs; a guest waits a little, then hears no. */final class Skates {    private final Semaphore permits;    private final Queue<String> shelf;    Skates(List<String> pairs) {        permits = new Semaphore(pairs.size());        shelf = new ConcurrentLinkedQueue<>(pairs);    }    String rent(long millis) throws InterruptedException {        if (!permits.tryAcquire(millis, TimeUnit.MILLISECONDS)) return null;        return shelf.remove();    }    void giveBack(String pair) {        shelf.add(pair);        permits.release();    }}/** The same calls as before. It owns three parts and no lock of its own. */final class Rink {    final Gate gate;    final Bench bench = new Bench();    final Skates skates;    Rink(int places, List<String> pairs) {        gate = new Gate(places);        skates = new Skates(pairs);    }}class Proof {    public static void main(String[] args) throws InterruptedException {        int guests = 40, places = 5;        Rink rink = new Rink(places, List.of("38-a", "38-b"));        CountDownLatch start = new CountDownLatch(1), done = new CountDownLatch(guests);        AtomicInteger inside = new AtomicInteger();        for (int i = 0; i < guests; i++)            new Thread(() -> {                try {                    start.await();                    if (rink.gate.enter()) inside.incrementAndGet();                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } finally {                    done.countDown();                }            }).start();        start.countDown();        done.await();        if (inside.get() != places) throw new AssertionError(inside.get());    }}
The same in C++
// Correctness. on_ice_ is guarded by m_. Rule: on_ice_ <= places_.class Gate {public:    explicit Gate(int places) : places_(places) {}    bool enter() {        std::lock_guard<std::mutex> hold(m_);        if (on_ice_ >= places_) return false;        ++on_ice_;        return true;    }    void leave() {        std::lock_guard<std::mutex> hold(m_);        if (on_ice_ == 0) throw std::logic_error("nobody is on the ice");        --on_ice_;    }private:    std::mutex m_;    const int places_;    int on_ice_ = 0;};// Coordination. The sharpener hands over, the desk waits.class Bench {public:    void put_ready(std::string pair) {        {            std::lock_guard<std::mutex> hold(m_);            ready_.push_back(std::move(pair));        }        arrived_.notify_one();    }    std::optional<std::string> take_ready(std::chrono::milliseconds patience) {        std::unique_lock<std::mutex> hold(m_);        if (!arrived_.wait_for(hold, patience, [this] { return !ready_.empty(); }))            return std::nullopt;        std::string pair = std::move(ready_.front());        ready_.pop_front();        return pair;    }private:    std::mutex m_;    std::condition_variable arrived_;    std::deque<std::string> ready_;     // a real one is bounded too};// Scarcity. C++20 has std::counting_semaphore. Here the shelf itself is the count.class Skates {public:    explicit Skates(std::vector<std::string> pairs) : shelf_(std::move(pairs)) {}    std::optional<std::string> rent(std::chrono::milliseconds patience) {        std::unique_lock<std::mutex> hold(m_);        if (!returned_.wait_for(hold, patience, [this] { return !shelf_.empty(); }))            return std::nullopt;        std::string pair = std::move(shelf_.back());        shelf_.pop_back();        return pair;    }    void give_back(std::string pair) {        {            std::lock_guard<std::mutex> hold(m_);            shelf_.push_back(std::move(pair));        }        returned_.notify_one();    }private:    std::mutex m_;    std::condition_variable returned_;    std::vector<std::string> shelf_;};// The same calls as before. It owns three parts and no lock of its own.struct Rink {    Gate gate;    Bench bench;    Skates skates;    Rink(int places, std::vector<std::string> pairs)        : gate(places), skates(std::move(pairs)) {}};int main() {    const int guests = 40, places = 5;    Rink rink(places, {"38-a", "38-b"});    std::atomic<bool> start{false};    std::atomic<int> inside{0};    std::vector<std::thread> threads;    for (int i = 0; i < guests; ++i)        threads.emplace_back([&] {            while (!start) std::this_thread::yield();            if (rink.gate.enter()) ++inside;        });    start = true;    for (auto& t : threads) t.join();    if (inside != places) std::abort();}
The same in TypeScript
/** Correctness. Check and change with no await in between: one turn of the event loop. */class Gate {  private onIce = 0;  constructor(private readonly places: number) {}  enter(): boolean {    if (this.onIce >= this.places) return false;    this.onIce++;    return true;  }  leave() {    if (this.onIce === 0) throw new Error("nobody is on the ice");    this.onIce--;  }}/** Coordination. Whoever comes first waits: the pair or the desk. */class Bench {  private ready: string[] = [];  private waiting: ((pair: string) => void)[] = [];  putReady(pair: string) {    const next = this.waiting.shift();    if (next) next(pair);    else this.ready.push(pair);  }  takeReady(): Promise<string> {    const pair = this.ready.shift();    if (pair !== undefined) return Promise.resolve(pair);    return new Promise((resolve) => this.waiting.push(resolve));  }}/** Scarcity. The shelf is the count; a guest without a pair waits in a line. */class Skates {  private waiting: ((pair: string) => void)[] = [];  constructor(private shelf: string[]) {}  rent(): Promise<string> {    const pair = this.shelf.pop();    if (pair !== undefined) return Promise.resolve(pair);    return new Promise((resolve) => this.waiting.push(resolve));  }  giveBack(pair: string) {    const next = this.waiting.shift();    if (next) next(pair);    else this.shelf.push(pair);  }}/** The same calls as before. It owns three parts. */class Rink {  readonly gate: Gate;  readonly bench = new Bench();  readonly skates: Skates;  constructor(places: number, pairs: string[]) {    this.gate = new Gate(places);    this.skates = new Skates(pairs);  }}async function prove(guests = 40, places = 5) {  const rink = new Rink(places, ["38-a", "38-b"]);  const inside = await Promise.all(    Array.from({ length: guests }, async () => {      await Promise.resolve();      // let all the others start first      return rink.gate.enter();    }),  );  if (inside.filter(Boolean).length !== places) throw new Error("too many on the ice");}