Facebook Pixel

You are on level: Student

0%
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section

Bounded Queue Block/Wake Trace

Prerequisites: Condition Variables and Producer-Consumer Queues, Mutexes, Lock Scope, and Contention

The feed thread puts AAPL updates into a queue, and the strategy thread takes them out. The article's queue can grow without limit; this one is bounded. Trace every put, take, block, and wakeup that a scheduler script causes.

  • Bounded blocking queue: holds at most C values and makes both sides wait. A consumer that finds it empty sleeps until a value arrives; a producer that finds it full sleeps until a slot frees up.
  • It uses one mutex and two condition variables, one per reason to wait:
    • producers wait on not_full, and every completed take notifies it;
    • consumers wait on not_empty, and every completed put notifies it.
void put(int v) {
    std::unique_lock<std::mutex> lock(m);
    while (q.size() == capacity) not_full.wait(lock);  // the predicate loop
    q.push_back(v);
    lock.unlock();
    not_empty.notify_one();                            // a value arrived
}

int take() {
    std::unique_lock<std::mutex> lock(m);
    while (q.empty()) not_empty.wait(lock);
    int v = q.front();
    q.pop_front();
    lock.unlock();
    not_full.notify_one();                             // a slot freed up
    return v;
}

With real threads, the call order changes from run to run. This problem removes the threads: it is a deterministic, single-threaded simulation of the queue above, driven by a scheduler script whose commands name the thread that runs next and what it does.

What to implement

  • process_commands(capacity, mode, commands) returns the printed lines, one per event, in the order the events happen.
  • On stdin: the capacity C, the mode (notify_one or notify_all), the number of commands Q, then the Q commands, one per line.
  • There are three parts. One solution must pass all ten tests.
CommandMeaning
T PUT vThread T tries to put the integer v
T TAKEThread T tries to take the oldest value
STATEPrint the queue and both wait queues
SPURIOUS TThread T wakes up with no notify (Part 3)
Printed lineWhen
PUT T vThread T appends v to the queue
TAKE T vThread T removes v from the front of the queue
BLOCK TThread T joins the back of a wait queue
WAKE TThread T leaves a wait queue
ERROR T BLOCKEDA PUT or TAKE names a blocked thread
ERROR T NOT_BLOCKEDA SPURIOUS names a running thread (Part 3)

STATE output

STATE queue=[...] not_full=[...] not_empty=[...]
  • Each list is oldest first, with commas and no spaces. An empty list is [].
  • queue lists values and not_empty lists thread names.
  • not_full lists each waiting producer as name:value with its pending value. In the example below, while P2 is blocked on its put of 12, the list is not_full=[P2:12].

The model

  • Each thread is running or blocked. Every thread starts out running, so a name the script has not used before belongs to a running thread.
  • A blocked thread sits in the wait queue of one condition variable: the threads waiting on it, oldest first.
  • The C++ standard promises no order for waking waiters. The simulation uses first-in, first-out order, so every script has exactly one correct output.
  • A blocked producer keeps its pending value. That value is not in the queue until the put completes.
  • A PUT or TAKE from a blocked thread prints ERROR T BLOCKED and changes nothing. A blocked thread is asleep inside wait() and cannot run code, so the line is a script mistake, not an operation.

Every PUT and TAKE is an attempt, one pass through the body of the predicate loop:

AttemptPredicateIf it holdsIf it fails
putthe queue holds fewer than C valuesappend the value at the back, print PUT T v, notify not_emptyprint BLOCK T, join the back of not_full
takethe queue is not emptyremove the front value, print TAKE T v, notify not_fullprint BLOCK T, join the back of not_empty

A notify on an empty wait queue does nothing, as a notification with no waiter evaporates in the article. Otherwise it removes waiters from the front and prints WAKE T for each: notify_one removes the oldest (Part 1), notify_all all of them (Part 2).

A woken thread repeats its attempt with its pending operation: the re-check of the while condition after wait() returns.

  • Woken threads re-check one at a time, in wake order, all before the next command runs.
  • An operation completed by a woken thread notifies exactly like one completed by a command.
  • A real woken thread would first reacquire the mutex, and another thread could run in the meantime. The simulation simplifies this: woken threads re-check before any other thread runs.

Part 1: notify_one

  1. The mode is notify_one, so each notify wakes only the oldest waiter.
  2. Nothing runs between that notify and the re-check, so in this part the re-check always succeeds.
  3. A woken producer appends its pending value behind the values already queued. A woken consumer takes the value at the front.
  4. A thread that blocks again later joins the back of the wait queue, behind every thread already waiting.

Limits

  • C and Q are between 1 and 105. The output has at most 2 · 105 lines.
  • Values are integers between -109 and 109, written without leading zeros or a plus sign.
  • Thread names have 1 to 8 letters and digits and are never STATE or SPURIOUS. Names such as P1 and C1 are only a convention: any thread may put and take.

Tests 1–4 cover this part. They all use notify_one.

Part 2: notify_all

Add the notify_all mode:

  1. A notify removes every thread from the wait queue, oldest first, and prints a WAKE line for each before any of them re-checks.
  2. The woken threads re-check in that order, each seeing the queue as the previous one left it.
  3. The first takes the freed slot or the new value.
  4. The others find their predicate false, print BLOCK, and rejoin the back of the wait queue, keeping their order relative to each other.

This is the article's case where another thread takes the item first, and it is why the wait sits inside a while loop rather than an if.

Tests 5–7 cover this part. They all use notify_all.

Part 3: Spurious wakeups

Add SPURIOUS T: thread T returns from wait() with no notify, which the standard permits.

  1. If T is running, including a name the script has not used before, print ERROR T NOT_BLOCKED and change nothing.
  2. Otherwise T leaves its wait queue from wherever it stands, prints WAKE T, and re-checks like any woken thread.
  3. In this simulation that re-check always fails, so T prints BLOCK T and rejoins the back of the same wait queue, losing its place.

The re-check fails because a producer waits only while the queue is full and a consumer only while it is empty: every notify hands the freed slot or new value to a woken thread before the next command runs.

  • Under notify_one, the lost place changes which thread a later notify wakes.
  • Under notify_all, it changes the order of the re-checks, and so which thread gets the slot or value.
  • A thread that tested its predicate with if instead of while would go on to put into a full queue or take from an empty one.

Tests 8–10 cover this part. Tests 8 and 9 use notify_one, and test 10 uses notify_all.

Example
Input
2
notify_one
10
P1 PUT 10
P1 PUT 11
P2 PUT 12
P2 PUT 13
C1 TAKE
STATE
C1 TAKE
C1 TAKE
C2 TAKE
P1 PUT 14
Output
PUT P1 10
PUT P1 11
BLOCK P2
ERROR P2 BLOCKED
TAKE C1 10
WAKE P2
PUT P2 12
STATE queue=[11,12] not_full=[] not_empty=[]
TAKE C1 11
TAKE C1 12
BLOCK C2
PUT P1 14
WAKE C2
TAKE C2 14
Explanation

The queue holds two values. P1 fills it with 10 and 11, so P2's put of 12 blocks. P2 joins not_full holding 12, and its next command is a script mistake that prints ERROR P2 BLOCKED.

C1's take removes 10 and notifies not_full. P2 wakes, re-checks, finds a free slot, and appends 12 behind 11, which STATE confirms.

C1 then takes 11 and 12, and each notify finds no waiter. C2's take finds the queue empty and blocks. When P1 puts 14, the notify on not_empty wakes C2, which re-checks and takes 14 before the next command.