Skip to content

Backpressure and bounded queues

Difficulty: Advanced

Key concepts

  • backpressure
  • bounded queue
  • overflow policy
  • producer contract
  • consumer contract
  • high-water mark
  • std::counting_semaphore
  • RAII permit
  • resource pool
  • Why a queue between threads must have a limit, and what backpressure is.
  • The three things a full queue can do: block the producer, reject the new item, or drop an old one, and how to choose.
  • How to write the producer and consumer contracts of a queue, and how closing a queue shuts a pipeline down.
  • How to limit how many threads use a scarce resource at once with std::counting_semaphore, wrapped in an RAII permit.

Thread safety described three concurrency concerns: correctness (shared state stays consistent), coordination (threads hand work to each other), and scarcity (limited resources are shared without being overwhelmed). This page is about the third. A queue lets a fast thread hand work to a slow one without waiting. That is its value, and also its danger: the fast thread never learns that the slow one is falling behind.

The worker pool on the previous page queues every job it is given. If jobs arrive at 1,000 a second and the workers finish 800 a second, the queue grows by 200 a second. After an hour it holds 720,000 jobs, and a job added then waits 15 minutes (720,000 ÷ 800 a second) before it starts; every further hour adds another 15 minutes. Nothing fails until the process runs out of memory, long after the overload began, and far from its cause.

// An unbounded queue: correct under the rules of the earlier pages, but
// it has no limit, so a slow consumer makes it grow without end.
class EventQueue {
public:
void push(Event event) {
{
const std::scoped_lock lock(mutex_); // guards events_
events_.push_back(std::move(event)); // never says no
} // unlocked before waking a consumer
not_empty_.notify_one();
}
// ...
private:
std::mutex mutex_;
std::condition_variable not_empty_; // consumers wait here
std::deque<Event> events_; // no size limit: the problem
};

This code is illustrative and was not compiled.

Nothing in this class is a data race or a deadlock. It is correct by the rules of the earlier pages, and still wrong, because it has no answer to one question: what happens when the consumer cannot keep up? “Keep everything” is an answer, but a bad one chosen by default.

Backpressure is the answer made explicit: when the consumer falls behind, that fact travels back to the producers, which then wait, give up, or lose something on purpose. A bounded queue is the simplest way to get it. It holds at most a fixed number of items, and its push must say what happens when it is full.

A photo service has three streams of work, each with one consumer thread, and one slow outside service:

  • Q1. Uploads. A user’s request asks for a thumbnail. If the thumbnail queue is full, the user should hear “busy, try again” at once, not wait with a spinning page.
  • Q2. Sensor readings. A device reports its temperature many times a second. The display shows the latest values; old readings are worthless once newer ones exist.
  • Q3. Audit events. Every change to a photo’s permissions is written to an audit log. None may be lost, even if the log writer is slow.
  • Q4. Memory used by the queues is bounded, whatever the producers do.
  • Q5. Overflow is visible: the service can report how full each queue has been and how many items were refused or dropped.
  • Q6. At shutdown, consumers finish what is queued and then stop.
  • Q7. Exports go to an outside service that allows at most two connections at once from this program.

The first three requirements are the same question with three different answers. What to do when full is not a property of queues; it is a decision about what the items are worth and who can wait:

Policy When full, push… The producer… What is lost Fits
Block waits until a consumer makes room slows down to the consumer’s speed nothing; the producer’s time Q3: every item matters, and the producer can wait
Reject returns at once, refusing the new item learns at once, and decides what to do the new item, unless the caller kept a copy Q1: a caller who can be told “busy”
Drop oldest discards the oldest item to make room never waits and is never refused old items, counted Q2: only recent items matter

There are other policies, such as dropping the newest item instead, or blocking for at most a time limit and then rejecting. They are variations of these three. Each one moves the cost of overload somewhere: onto the producer’s time (block), onto the producer’s caller (reject), or onto the data (drop). No policy makes the cost disappear; the only choice is where it lands.

The member functions classify as usual. push is a command for producers; pop is a command for consumers, which also returns what it took; close is a lifecycle command; stats is a query.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

bounded_queue.hpp
// What push() does when the queue is full. Chosen once, when the queue is
// made, by the code that knows what the items are worth.
enum class WhenFull {
block, // wait until a consumer makes room
reject, // refuse the new item at once; the producer decides
drop_oldest, // make room by discarding the oldest queued item
};
// What happened to one push(). push() is [[nodiscard]], so a caller that
// ignores this gets a compiler warning: under reject, ignoring it would
// mean losing an item without noticing.
enum class PushResult {
accepted,
accepted_after_drop, // accepted, and the oldest item was discarded
rejected, // full, and the policy is WhenFull::reject
closed, // close() was called; the item was not queued
};
// Numbers that make overflow visible. stats() returns a copy, all taken
// under one lock, so the four numbers describe the same moment.
struct QueueStats {
std::size_t size = 0; // items queued right now
std::size_t high_water = 0; // the largest size ever reached
std::size_t dropped = 0; // items discarded by drop_oldest
std::size_t rejected = 0; // items refused by reject
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

bounded_queue.hpp
// Thread safety: safe. Any number of producers may call push() and any
// number of consumers pop() at the same time.
//
// Producer contract: push() blocks only under WhenFull::block. Under the
// other policies it never waits, and its result says what happened.
// Consumer contract: pop() waits for an item, and returns std::nullopt
// only once the queue is closed and empty. Consumers that loop until
// std::nullopt together receive, each exactly once, every accepted item
// that was not later dropped.
//
// push() takes the item by value: a rejected or closed item is destroyed,
// so a caller that may want to retry must keep its own copy.
template <typename T>
class BoundedQueue {
// Moving an item in or out must not throw, or a failure halfway through
// push() or pop() could leave an item in neither place.
// static_assert is checked by the compiler: BoundedQueue<T> does not
// compile for a T whose move constructor may throw.
static_assert(std::is_nothrow_move_constructible_v<T>);
public:
// Makes an empty, open queue that holds at most `capacity` items and
// follows `policy` when full. Throws std::invalid_argument for a
// capacity of 0, which no push could ever fit into.
BoundedQueue(std::size_t capacity, WhenFull policy) : capacity_(capacity), policy_(policy) {
if (capacity == 0) {
throw std::invalid_argument("a bounded queue needs room for one item");
}
}
// Not copyable: a copy would have its own mutex and items, and threads
// sharing "the queue" must all share this one. Declaring the copy
// operations also means no move is generated, so it cannot be moved.
BoundedQueue(const BoundedQueue&) = delete;
BoundedQueue& operator=(const BoundedQueue&) = delete;
// Producers: offers one item; the result says what happened to it.
[[nodiscard]] PushResult push(T item);
// Consumers: takes the oldest item, waiting for one if the queue is
// empty. An empty optional means "closed, and nothing left".
std::optional<T> pop();
// No item is accepted after this. Wakes every waiting producer and
// consumer; consumers still receive the items already queued.
void close();
[[nodiscard]] QueueStats stats() const;
[[nodiscard]] std::size_t capacity() const noexcept { return capacity_; }
private:
// One mutex guards everything that changes: the items, the closed flag,
// and the numbers. mutable, because stats() is const and locks it.
mutable std::mutex mutex_;
std::condition_variable not_full_; // producers wait here (block policy)
std::condition_variable not_empty_; // consumers wait here
std::deque<T> items_; // guarded by mutex_; at most capacity_ when unlocked
bool closed_ = false; // guarded by mutex_
QueueStats stats_; // guarded by mutex_; size filled in by stats()
// Set once by the constructor and never changed, so they need no lock.
const std::size_t capacity_;
const WhenFull policy_;
};
  • The policy is fixed when the queue is made. One queue carries one kind of item, and the decision about that kind belongs to the code that builds the queue, not to each producer. A producer cannot choose the wrong policy at one call site.
  • push returns a PushResult and is [[nodiscard]]. Under the reject policy, ignoring the result means losing an item without noticing. Under the block policy the only refusal is closed. In the demo that cannot happen, because the producer’s own guard is the only thing that closes the queue, so the demo discards the result with static_cast<void>(queue.push(item)), which says so. In general a producer must handle closed too.
  • The contracts are in the header. The producer contract says when push may wait. The consumer contract says what std::nullopt means: closed and empty. Consumers that loop until they see std::nullopt together receive, each exactly once, every accepted item that was not later dropped. With several consumers, no single one sees every item, and under drop oldest an accepted item can still be dropped later.
  • Two condition variables. Producers wait for “not full” and consumers wait for “not empty”. With one condition variable shared by both, a notify_one meant for a consumer could wake a producer instead, which would find the queue still full and go back to sleep, while the consumer that could have made progress keeps sleeping. Both sides can be waiting at once because a woken thread is not necessarily the next to run: with room for one item, two producers and a consumer can all be asleep after a few interleavings. If the wrong one gets the last notification, every thread sleeps, a deadlock. (A version with one condition variable and notify_one, room for one item, and three producers and three consumers hung in every run we tried.) One condition variable with notify_all would be correct, but it wakes every thread for every change.
  • std::is_nothrow_move_constructible_v<T> is required, so that moving an item into or out of the queue cannot fail halfway.
  • QueueStats is copied out under the lock (Q5), as in Thread safety: the high-water mark, the drop count, and the reject count are one consistent picture.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

bounded_queue.hpp
// Offers `item` to the queue. Under block, waits for room (or for close).
// Under reject and drop_oldest, never waits. Returns what happened. The
// item is taken by value: the caller's argument is copied or moved into
// `item`, and if it is refused, it is destroyed when push returns.
template <typename T>
PushResult BoundedQueue<T>::push(T item) {
// Locals are destroyed in reverse order, so `discarded` (declared
// first) outlives the lock below and is destroyed after it.
std::optional<T> discarded; // destroyed after the lock is released
PushResult result = PushResult::accepted;
{ // the lock's scope
// unique_lock, because wait() must be able to unlock and relock it.
std::unique_lock lock(mutex_);
if (policy_ == WhenFull::block) {
// Sleeps until there is room or the queue is closed. wait()
// checks the condition first, releases mutex_ while it sleeps,
// relocks before it returns, and rechecks after every wakeup,
// including a spurious one. [this] lets the lambda read members.
not_full_.wait(lock, [this] { return closed_ || items_.size() < capacity_; });
}
// From here on mutex_ is held, under every policy.
if (closed_) {
return PushResult::closed; // the item is destroyed on the way out
}
if (items_.size() == capacity_) { // full (never true under block)
if (policy_ == WhenFull::reject) {
++stats_.rejected;
return PushResult::rejected;
}
// drop_oldest: add the new item first, so that if push_back
// throws, nothing has been discarded (strong guarantee).
items_.push_back(std::move(item));
// Moves the oldest item's contents out into `discarded` (cannot
// throw: T's move is noexcept), then removes the moved-from
// shell. The deque is back to exactly capacity_ items.
discarded.emplace(std::move(items_.front()));
items_.pop_front();
++stats_.dropped;
result = PushResult::accepted_after_drop;
} else {
items_.push_back(std::move(item)); // room: just add it
}
stats_.high_water = std::max(stats_.high_water, items_.size());
} // mutex_ unlocked here
// One item was added, so one waiting consumer can take it. Notified
// after unlocking, so the consumer does not wake only to wait for the
// mutex.
not_empty_.notify_one();
return result;
} // `discarded` is destroyed here, unlocked; `item` (moved from) as push returns
How this code works: BoundedQueue::push, one policy at a time

Every call starts the same way: lock mutex_. What follows depends on the policy, which never changes after the queue is made.

  1. Block only: wait for room. not_full_.wait returns at once if the queue is closed or has room. Otherwise it releases mutex_ and sleeps, as one step, until a pop or close notifies not_full_ (or it wakes spuriously); then it locks mutex_ again and checks again. If another producer took the room first, or nothing changed, it goes back to sleep. When it returns, the mutex is held and the queue is closed or has room.
  2. Closed? Refuse. Under every policy, a closed queue returns PushResult::closed. The early return unlocks mutex_ as lock is destroyed.
  3. Full? Under block this cannot be true any more, because step 1 waited for room. Under the other two policies:
    • reject counts the refusal and returns PushResult::rejected;
    • drop oldest appends the new item, moves the oldest one out into discarded, removes the moved-from shell, and counts a drop.
  4. Not full: append the item.
  5. Record the high-water mark, close the block (unlocking mutex_), then wake one consumer with notify_one.

The readings queue in the demo has room for three and the drop oldest policy. Pushing 1 to 5 goes like this:

Push Queue before Full? What happens Queue after Result
1 empty no appended 1 accepted
2 1 no appended 1 2 accepted
3 1 2 no appended 1 2 3 accepted
4 1 2 3 yes 4 appended (briefly 1 2 3 4), 1 dropped 2 3 4 accepted_after_drop
5 2 3 4 yes 5 appended (briefly 2 3 4 5), 2 dropped 3 4 5 accepted_after_drop

The high-water mark ends at 3: it is updated after the drop, so the brief fourth item never counts. dropped ends at 2. Popping after the close gives 3, 4, 5, as the demo’s output shows.

  • Only the block policy waits. Its predicate includes closed_, so a producer stuck behind a full queue wakes when the queue is closed, and gets PushResult::closed instead of waiting forever.
  • Reject counts and returns while it still holds the lock. The item, owned by the parameter, is destroyed after the lock has been released.
  • A refused item is gone. Because push takes the item by value, a rejected or closed item is destroyed, and a move-only item, such as a std::unique_ptr, cannot be tried again. A caller that may retry must keep its own copy, or the queue must hand the item back, for example with a try_push(T& item) that moves from item only when it accepts it.
  • Drop oldest adds before it removes. If push_back throws, for example because the deque cannot allocate, nothing has been discarded: the strong guarantee from Exception safety. Inside the lock the deque briefly holds one item more than its capacity, which no other thread can see.
  • The discarded item is destroyed after the lock is released. Its contents are moved into discarded, a local declared before the lock, and released when push returns. Only the moved-from shell left in the deque is destroyed inside the lock, by pop_front, which is normally trivial. An item’s destructor is code the queue does not control, so its real work does not run under the queue’s mutex.
  • The high-water mark is updated on every accepted push. It is the one number that shows how close the queue came to its limit, even if it is empty when someone looks. It never goes down, so a monitor that wants “the highest this minute” needs a way to read and reset it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

bounded_queue.hpp
// Takes the oldest item, waiting while the queue is empty and open. After
// close(), it still returns the queued items one by one, and only when
// none are left returns std::nullopt.
template <typename T>
std::optional<T> BoundedQueue<T>::pop() {
std::optional<T> item; // empty until an item is moved into it
{
std::unique_lock lock(mutex_);
// Sleeps until there is an item or the queue is closed; it releases
// mutex_ while asleep and rechecks the condition after each wakeup.
not_empty_.wait(lock, [this] { return closed_ || !items_.empty(); });
// Woken with an empty queue means the queue was closed.
if (items_.empty()) {
return std::nullopt; // closed, and every item has been taken
}
// There is an item (whether or not the queue is closed): move it
// out, then remove the moved-from shell from the front.
item.emplace(std::move(items_.front()));
items_.pop_front();
} // mutex_ unlocked here
not_full_.notify_one(); // one item out, room for one producer
return item;
}
// Marks the queue closed. Calling it again does no harm. Queued items
// stay queued for the consumers.
template <typename T>
void BoundedQueue<T>::close() {
{
// closed_ is changed under mutex_, the mutex the waiters use, so a
// waiter cannot check it, miss the change, and then sleep forever.
const std::scoped_lock lock(mutex_);
closed_ = true;
}
// Wakes every waiter on both sides. Each rechecks its condition and
// finds closed_ true: a producer returns closed, and a consumer takes
// an item if one is left, or returns std::nullopt.
not_full_.notify_all();
not_empty_.notify_all();
}
// A copy of the numbers, taken under the lock, with the current size.
template <typename T>
QueueStats BoundedQueue<T>::stats() const {
const std::scoped_lock lock(mutex_);
QueueStats copy = stats_;
copy.size = items_.size(); // the size is not stored; it is read now
return copy;
}
  • pop waits for an item or for the close. Once closed, it keeps returning items until the queue is empty, and only then std::nullopt. That is how Q6 is met: closing does not discard.
  • pop notifies one producer after it releases the lock: one item out means room for one item in. Producers are not woken in the order they started waiting; a condition variable promises no fairness. Under the policies that never wait, nobody is waiting, and the notification costs little.
  • close wakes everyone. Every waiting producer must return closed, and every waiting consumer must recheck, so this is a notify_all on both condition variables.
  • Closing is the shutdown signal of a pipeline. Following the order from Asynchronous work, cancellation, and shutdown, the producers stop first, then the queue is closed, then the consumer drains it and returns, and only then is it joined. The close must happen on every path, which the guard below makes sure of.
Block policy: a producer waits at a full queue until the consumer makes room, and close lets the consumer drain and stop
Text description of the diagram

The queue has room for two items, and its policy is block. The producer pushes items 1 and 2, which fill it. Its push of item 3 finds the queue full, so the producer waits. The consumer pops item 1, which makes room, and the queue notifies a waiting producer; the push of item 3 is accepted. The producer then closes the queue; close notifies every waiting thread, although here no consumer is waiting, because the queue still holds two items. The consumer keeps popping: it gets item 2, then item 3, and then, because the queue is closed and empty, std::nullopt, which ends its loop. No item was lost, and the queue never held more than two.

Diagram source (Mermaid)
sequenceDiagram
participant P as Producer
participant Q as BoundedQueue, capacity 2
participant C as Consumer
P->>Q: push(1), accepted
P->>Q: push(2), accepted, now full
P->>Q: push(3)
Note over P,Q: full, so the producer waits on not_full
C->>Q: pop()
Q-->>C: item 1
Q->>P: notify not_full
Q-->>P: push(3) accepted
P->>Q: close()
Note over Q,C: close notifies everyone, no consumer is waiting here
C->>Q: pop()
Q-->>C: item 2
C->>Q: pop()
Q-->>C: item 3
C->>Q: pop()
Q-->>C: nullopt, closed and empty
Note over C: the consumer loop ends

If a producer throws before it calls close, the queue is never closed. The consumer waits in pop forever, and the std::jthread that owns it waits forever to join it: the program hangs instead of reporting the error. Closing is cleanup, so it belongs in a destructor:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

bounded_queue.hpp
// Closes a queue when it goes out of scope, on every path, including an
// exception. Declare it after the consumers' threads: it is then destroyed
// first, so the queue is closed before the threads are joined.
template <typename T>
class CloseOnExit {
public:
// Remembers the queue; does nothing else until it is destroyed.
explicit CloseOnExit(BoundedQueue<T>& queue) noexcept : queue_(&queue) {}
// Not copyable: one guard for one scope. A copy would close the queue
// when whichever copy was destroyed first.
CloseOnExit(const CloseOnExit&) = delete;
CloseOnExit& operator=(const CloseOnExit&) = delete;
// The whole point: leaving the scope, normally or by an exception,
// closes the queue, which lets blocked consumers finish.
~CloseOnExit() { queue_->close(); }
private:
BoundedQueue<T>* queue_; // not owned: the queue must outlive the guard
};
  • Declare the guard after the consumers’ threads. Locals are destroyed in reverse order, so the guard closes the queue first, and the threads are joined after it, once their consumers have drained the queue and returned.
  • The guard does not own the queue. It holds a pointer to a queue that must outlive it, like the permits below.

Q7 is a different kind of limit. Nothing is waiting in a line; the limit is on how many threads may use something at the same time. The tool for that is a counting semaphore: a counter of free permits, where taking one waits while the counter is zero, and giving one back wakes a waiter.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

slots.hpp
// A fixed number of permits for a scarce resource, such as connections to
// a slow service. Thread safety: safe. A Permit gives its slot back when
// it is destroyed, on every path, including an exception.
class Slots {
public:
// Throws std::invalid_argument unless 1 <= count <= the semaphore's max().
// checked(count) runs in the member initializer list, before the
// semaphore is built, so a bad count never reaches it.
explicit Slots(std::ptrdiff_t count) : free_(checked(count)) {}
// Proof that its owner holds one slot. Only Slots can make one (the
// constructor that takes a Slots& is private). Destroying it gives the
// slot back. [[nodiscard]] on the class: the compiler warns if a
// returned Permit is thrown away at once.
class [[nodiscard]] Permit {
public:
// Moving hands the slot to the new Permit. std::exchange returns
// other.slots_ and sets it to nullptr in one expression, so the
// moved-from Permit owns nothing and its destructor releases nothing.
Permit(Permit&& other) noexcept : slots_(std::exchange(other.slots_, nullptr)) {}
// No copies: one slot, one owner. Assignment is ruled out too, so a
// Permit always keeps the slot it was made with.
Permit(const Permit&) = delete;
Permit& operator=(const Permit&) = delete;
Permit& operator=(Permit&&) = delete;
// Gives the slot back on every path out of the owner's scope,
// including an exception. release() adds one free permit and wakes
// a thread waiting in acquire(), if there is one.
~Permit() {
if (slots_ != nullptr) { // nullptr: moved from, owns nothing
slots_->free_.release();
}
}
private:
friend class Slots; // lets Slots call the private constructor
explicit Permit(Slots& slots) noexcept : slots_(&slots) {}
Slots* slots_; // not owned: the Slots must outlive every Permit
};
// Waits until a slot is free.
// free_.acquire() takes one permit from the semaphore, sleeping while
// none is free. Only then is the Permit made, so a Permit always
// stands for a slot really taken. Making it cannot throw (noexcept).
[[nodiscard]] Permit acquire() {
free_.acquire();
return Permit(*this);
}
// Returns std::nullopt at once if every slot is taken. It may also,
// rarely, return std::nullopt when a slot is free, as the standard
// allows: treat std::nullopt as "not now".
[[nodiscard]] std::optional<Permit> try_acquire() {
if (!free_.try_acquire()) { // never waits
return std::nullopt;
}
return Permit(*this); // moved into the returned optional
}
private:
// Returns `count` unchanged if the semaphore can accept it; otherwise
// throws, because building std::counting_semaphore with a count above
// max() is undefined behavior. (A count of 0 is allowed by the
// semaphore, but Slots with no slots could never be used.)
static std::ptrdiff_t checked(std::ptrdiff_t count) {
if (count < 1 || count > std::counting_semaphore<>::max()) {
throw std::invalid_argument("Slots needs a count from 1 to the semaphore's maximum");
}
return count;
}
// The count of free slots. <> takes the default for the largest count
// it must support.
std::counting_semaphore<> free_;
};
How this code works: The life of one Permit

Take Slots export_slots(2) from the demo: the semaphore starts with 2 free permits.

  1. export_slots.acquire() calls free_.acquire(). If a permit is free, the count drops by one (from 2 to 1 for the first export) and the call returns at once; if the count is 0, the thread sleeps until another thread releases one.
  2. return Permit(*this) builds a Permit holding a pointer to export_slots. The caller writes const flow::Slots::Permit permit = export_slots.acquire();, and since C++17 that Permit is built straight into permit, with no copy or move.
  3. The export runs while permit exists. The slot is in use for exactly as long as permit is alive.
  4. permit is destroyed at the end of its scope. Its destructor sees a non-null pointer and calls free_.release(): the count goes back up by one, and a thread sleeping in step 1 can wake and take it.

With try_acquire(), step 1 never sleeps, and the Permit is moved into the returned std::optional. A move hands the pointer to the new Permit and leaves nullptr in the old one, so only one of them releases the slot. If anything throws while the export runs, step 4 still happens as the exception leaves the scope (as long as something catches it), which is the whole reason for the Permit class.

  • std::counting_semaphore<> starts with count permits. acquire takes one, waiting if there is none; release gives one back; try_acquire takes one only if it can do so at once.
  • The count is checked. The semaphore’s constructor requires a count from 0 to max(), and anything else is undefined behavior. So Slots checks it first, in a helper called from the member initializer list, and throws std::invalid_argument for a count below 1 or above max(). With the standard library used here (libstdc++), max() is 2,147,483,647, although the parameter is a std::ptrdiff_t.
  • A raw semaphore is easy to leak. A function that calls acquire() and then throws before release() loses a permit for good; lose two, and Q7’s limit of two blocks every export forever. So Slots hands out a Permit, an RAII object whose destructor releases, as RAII recommends for every resource.
  • A Permit can be moved but not copied, like a std::unique_lock: there is exactly one owner of each permit. The moved-from permit holds a null pointer and releases nothing.
  • [[nodiscard]] on the class warns when a caller writes slots.acquire(); alone, which would wait for a permit and give it back on the same line. The attribute does not reach through std::optional, so try_acquire is marked [[nodiscard]] itself.
  • try_acquire is the reject policy for a resource: a caller who must not wait gets std::nullopt and decides what to do. The standard allows try_acquire to fail now and then even when a permit is free, so treat std::nullopt as “not now”, not as “all taken”.
  • A permit must outlive the use of the resource, and the Slots object must outlive every permit, because each permit points to it.
Three bounded queues, each with the policy its items need, and two permits in front of the slow export service
Text description of the diagram

Request threads put thumbnail requests in the uploads queue, whose policy is reject; when it is full, the request thread is told at once and can answer the user. Request threads also put permission changes in the audit queue, whose policy is block, so no audit event is lost and the request thread waits if the audit writer falls behind. A device reader puts readings in the readings queue, whose policy is drop oldest, so the display always gets the newest readings. Each queue has its own consumer: the thumbnail worker, the audit writer, and the display. Separately, export threads must acquire one of two permits from a Slots object before they talk to the outside export service, so at most two exports use it at once.

Diagram source (Mermaid)
flowchart LR
R[Request threads] -- thumbnail requests --> U[uploads queue, reject]
R -- permission changes --> A[audit queue, block]
D[Device reader] -- readings --> S[readings queue, drop oldest]
U --> UT[thumbnail worker]
A --> AW[audit writer]
S --> SD[display]
E[Export threads] -- acquire a permit --> P[Slots, 2 permits]
P --> X[outside export service]
U -. rejected .-> R

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
// Reject: a user-facing request is refused at once, so the caller can
// answer "busy, try again" instead of making the user wait.
// Room for two, so the third upload finds the queue full. No consumer
// runs here, so nothing ever leaves the queue.
BoundedQueue<std::string> uploads(2, WhenFull::reject);
// Each name becomes its own std::string, `file`; push(file) copies it
// into push's parameter, so `file` itself is unchanged.
for (const std::string file : {"a.jpg", "b.jpg", "c.jpg"}) {
std::cout << "upload " << file << ": " << describe(uploads.push(file)) << '\n';
}
// Drop oldest: only the latest readings matter, so old ones make room.
// Room for three: readings 4 and 5 each push out the oldest (1, then 2).
BoundedQueue<int> readings(3, WhenFull::drop_oldest);
for (int reading = 1; reading <= 5; ++reading) {
std::cout << "reading " << reading << ": " << describe(readings.push(reading)) << '\n';
}
// Closed first, so that pop() returns std::nullopt once the queue is
// empty. On an open, empty queue pop() would wait forever, because no
// other thread is left to push.
readings.close();
std::cout << "readings kept:";
// The loop declares `reading` in its condition. An optional counts as
// true when it holds a value, so the loop stops at std::nullopt, and
// *reading is the int inside.
while (const auto reading = readings.pop()) {
std::cout << ' ' << *reading;
}
std::cout << '\n';
// Block: every audit event must arrive, so a fast producer waits for a
// slow consumer, and the queue never holds more than its capacity.
BoundedQueue<int> audit(2, WhenFull::block);
// Written only by the consumer thread, read by main() after the join.
std::vector<int> received;
{
// Declared first, so destroyed (and joined) last in this block.
std::jthread consumer([&audit, &received] {
while (const auto event = audit.pop()) {
std::this_thread::sleep_for(1ms); // a slow write
received.push_back(*event);
}
});
// Declared after the consumer, so destroyed first: at the closing
// brace it closes the queue, and only then is the consumer joined.
const flow::CloseOnExit close_audit(audit); // runs before the consumer is joined
for (int event = 1; event <= 20; ++event) {
// Waits while the queue is full. The only refusal under block is
// `closed`, which cannot happen here: only close_audit closes it.
static_cast<void>(audit.push(event));
}
} // the queue is closed, even if a push threw; the consumer drains it and is joined
// One producer and one consumer, so the events come out in the order
// they went in: 1, 2, ..., 20.
const bool in_order = std::is_sorted(received.begin(), received.end());
std::cout << "audit events received: " << received.size()
<< (in_order ? ", in order" : ", out of order") << '\n';
const bool bounded = audit.stats().high_water <= audit.capacity();
std::cout << "audit queue " << (bounded ? "never held more than 2" : "grew too large") << '\n';
// A scarce resource: six exports, at most two at once.
flow::Slots export_slots(2);
std::atomic<int> running{0}; // exports inside the limit right now
std::atomic<int> most_at_once{0}; // the largest value `running` reached
{
std::vector<std::jthread> exports;
for (int i = 0; i < 6; ++i) {
// [&] captures export_slots, running, and most_at_once by
// reference; all three outlive the threads.
exports.emplace_back([&] {
// Waits here while two other exports hold the slots. The
// Permit is the slot: it is given back when it is destroyed.
const flow::Slots::Permit permit = export_slots.acquire();
// fetch_add returns the value before the add, so + 1 is
// how many are running now, counting this one.
const int now = running.fetch_add(1) + 1;
// Raise most_at_once to `now` if `now` is larger, safely
// while other threads may do the same. compare_exchange_weak
// stores `now` only if most_at_once still equals `seen`;
// otherwise it copies the current value into `seen` and
// returns false, and the loop tries again. It may also fail
// for no reason (that is what "weak" allows), which only
// costs another pass. The loop stops once the store worked
// or `now` is no longer larger. The body is empty on purpose.
int seen = most_at_once.load();
while (now > seen && !most_at_once.compare_exchange_weak(seen, now)) {
}
std::this_thread::sleep_for(5ms); // stands in for the export
running.fetch_sub(1);
// Had code here thrown, a catch further out in this lambda would
// find the permit already released by unwinding. An exception
// that escapes the thread's function calls std::terminate instead.
}); // the permit is released here, as the lambda's scope ends
}
} // all six exports joined
std::cout << "exports running at once: " << (most_at_once.load() <= 2 ? "never more than 2" : "too many")
<< '\n';
}
Expected output
upload a.jpg: accepted
upload b.jpg: accepted
upload c.jpg: rejected
reading 1: accepted
reading 2: accepted
reading 3: accepted
reading 4: accepted, oldest dropped
reading 5: accepted, oldest dropped
readings kept: 3 4 5
audit events received: 20, in order
audit queue never held more than 2
exports running at once: never more than 2
  • The third upload is rejected at once (Q1), and the program could answer the user.
  • Readings 1 and 2 are dropped to make room for 4 and 5 (Q2); the queue keeps the three newest.
  • All 20 audit events arrive, in order (Q3), although the producer is much faster than the consumer, which sleeps a millisecond per event. The producer could push only as fast as the consumer made room, and the queue never held more than its capacity (Q4).
  • The guard closes the audit queue at the closing brace, and the consumer stops once it has drained the queue (Q6). The std::jthread is joined after the guard is destroyed and before received is read. If a push threw, the guard would still close the queue as the exception left the block, so the consumer would stop and be joined instead of hanging. (An exception that is never caught ends the program, and whether locals are destroyed first is then up to the implementation; the guard helps wherever the exception is caught.)
  • Never more than two exports ran at once (Q7). The program checks the limit rather than printing the largest number seen, because how many exports overlapped depends on scheduling.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_bounded_queue.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(actual, expected) records one
// if the two values are not equal, and prints both. They come from the
// site's small test header, lld_test.hpp, and must run on the main thread.
//
// queue.pop() == 1 compares a std::optional<int> with an int: it is true
// only if the optional holds a value and that value is 1.
// Sets up a full queue with room for two. Proves a third push is refused
// at once and counted, and that a pop makes room for a push again.
LLD_TEST(reject_refuses_when_full_and_accepts_again_after_a_pop) {
BoundedQueue<int> queue(2, WhenFull::reject);
LLD_CHECK(queue.push(1) == PushResult::accepted);
LLD_CHECK(queue.push(2) == PushResult::accepted);
LLD_CHECK(queue.push(3) == PushResult::rejected);
LLD_CHECK(queue.pop() == 1);
LLD_CHECK(queue.push(4) == PushResult::accepted);
LLD_CHECK_EQ(queue.stats().rejected, 1u);
}
// Pushes 1 to 5 into room for three. Proves the two oldest, 1 and 2, were
// dropped and counted, and that 3, 4, and 5 remain, oldest first.
LLD_TEST(drop_oldest_keeps_the_newest_items) {
BoundedQueue<int> queue(3, WhenFull::drop_oldest);
for (int i = 1; i <= 5; ++i) {
// push is [[nodiscard]]; static_cast<void> says "ignored on purpose".
static_cast<void>(queue.push(i));
}
LLD_CHECK_EQ(queue.stats().dropped, 2u);
LLD_CHECK(queue.pop() == 3);
LLD_CHECK(queue.pop() == 4);
LLD_CHECK(queue.pop() == 5);
}
// A producer thread pushes 1, 2, 3 into room for two. Proves the third
// push waits until the main thread pops, and then finishes.
LLD_TEST(block_makes_the_producer_wait_until_there_is_room) {
BoundedQueue<int> queue(2, WhenFull::block);
// How many pushes have returned. Atomic, because the producer writes it
// while the main thread reads it.
std::atomic<int> pushed{0};
std::jthread producer([&queue, &pushed] {
for (int i = 1; i <= 3; ++i) {
static_cast<void>(queue.push(i));
pushed.store(i);
}
});
// Waits until two pushes have returned. yield() lets other threads run
// instead of spinning flat out.
while (pushed.load() < 2) {
std::this_thread::yield();
}
// Gives a wrongly non-blocking third push time to finish, so that the
// check below would catch it. A correct queue passes whatever the timing.
std::this_thread::sleep_for(20ms);
LLD_CHECK_EQ(pushed.load(), 2); // the third push cannot finish: the queue is full
LLD_CHECK(queue.pop() == 1);
// join() waits for the producer to end. Calling it here, rather than
// leaving it to the jthread's destructor, lets the checks below run
// after the producer is done.
producer.join(); // the pop made room, so the third push finishes
LLD_CHECK_EQ(pushed.load(), 3);
LLD_CHECK_EQ(queue.stats().high_water, 2u); // never more than two queued
}
  • Each policy is tested on its own: reject refuses a third item and accepts again after a pop; drop oldest keeps 3, 4, and 5 and counts two drops.
  • Blocking is tested by what cannot happen. Once the producer has pushed twice into a queue with room for two, its third push cannot finish until something is popped. The test waits a little and checks that the count is still 2. That check cannot fail if the queue is correct, whatever the timing; a queue that did not block would make it fail almost always.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_bounded_queue.cpp
// One thread only. Proves that after close() a push is refused, the items
// already queued still come out in order, and then pop() says "done".
LLD_TEST(close_lets_consumers_drain_then_tells_them_to_stop) {
BoundedQueue<std::string> queue(4, WhenFull::block);
static_cast<void>(queue.push("a"));
static_cast<void>(queue.push("b"));
queue.close();
LLD_CHECK(queue.push("c") == PushResult::closed);
LLD_CHECK(queue.pop() == "a");
LLD_CHECK(queue.pop() == "b");
LLD_CHECK(!queue.pop().has_value()); // std::nullopt: closed and empty
}
// Sets up a producer stuck on a full queue and a consumer stuck on an
// empty one. Proves close() wakes both, with "closed" and "no item".
LLD_TEST(close_wakes_a_blocked_producer_and_a_blocked_consumer) {
BoundedQueue<int> full(1, WhenFull::block);
BoundedQueue<int> empty(1, WhenFull::block);
static_cast<void>(full.push(1)); // room for one, so `full` is now full
PushResult producer_result = PushResult::accepted; // read after the join
bool consumer_got_item = true; // read after the join
{
// Each thread writes its own plain variable. The main thread reads
// them only after the joins, which makes the writes visible.
std::jthread producer([&] { producer_result = full.push(2); }); // waits: full
std::jthread consumer([&] { consumer_got_item = empty.pop().has_value(); }); // waits
std::this_thread::sleep_for(20ms); // likely, not certain, that both are waiting
full.close();
empty.close();
} // both threads have returned, so both are joined here
LLD_CHECK(producer_result == PushResult::closed);
LLD_CHECK(!consumer_got_item);
}
// A producer pushes one item and then throws. Proves the CloseOnExit guard
// closes the queue as the exception leaves the block, so the consumer gets
// the item, stops, and can be joined.
LLD_TEST(close_on_exit_closes_the_queue_when_a_producer_throws) {
BoundedQueue<int> queue(2, WhenFull::block);
int received = 0; // read after the join
try {
std::jthread consumer([&] {
while (queue.pop()) {
++received;
}
});
const flow::CloseOnExit close_queue(queue); // destroyed before consumer
static_cast<void>(queue.push(1));
throw std::runtime_error("producer failed");
// Leaving the try block by this throw destroys its locals in
// reverse order: close_queue first (the queue closes), then
// consumer (which finishes its loop and is joined).
} catch (const std::runtime_error&) {
} // without the guard, the consumer's join as the throw left `try` would hang
LLD_CHECK_EQ(received, 1);
}
  • Close lets consumers drain: items pushed before the close come out, then std::nullopt, and a push after the close is refused.
  • Close wakes blocked threads. The test gives a producer a full queue and a consumer an empty one, waits, then closes both. The sleep makes it likely, not certain, that both are already waiting. If one is not, it finds the queue closed when it arrives, and the test still passes: the result is the same either way, so the test is not flaky, but it does not always test the wakeup.
  • The queue is closed even when a producer throws. A producer holds a CloseOnExit guard and throws partway through. The consumer still receives the items pushed before the throw, then std::nullopt, and its thread can be joined. Without the guard, that join would wait forever.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_bounded_queue.cpp
LLD_TEST(many_producers_and_consumers_lose_nothing_and_keep_each_producers_order) {
constexpr int producers = 4;
constexpr int per_producer = 2000;
BoundedQueue<int> queue(8, WhenFull::block);
// One vector per consumer, so no two threads ever write the same
// vector. `received` itself is not resized while the threads run.
std::vector<std::vector<int>> received(3); // one vector per consumer
{
std::vector<std::jthread> consumers;
for (std::size_t c = 0; c < received.size(); ++c) {
// &mine = received[c] is an init-capture: inside the lambda,
// `mine` is a reference to this consumer's own vector.
consumers.emplace_back([&queue, &mine = received[c]] {
while (const auto item = queue.pop()) {
mine.push_back(*item);
}
});
}
{
std::vector<std::jthread> senders;
for (int p = 0; p < producers; ++p) {
senders.emplace_back([&queue, p] {
for (int i = 0; i < per_producer; ++i) {
// Each producer sends its own block of 2000 numbers,
// in increasing order (producer 0: 0 to 1999,
// producer 1: 2000 to 3999, ...). So every item is
// unique, and item / 2000 says which producer sent it.
static_cast<void>(queue.push(p * per_producer + i));
}
});
}
} // every producer has finished
// Only now, with nothing left to send, is the queue closed.
queue.close();
} // every consumer has drained the queue and stopped
std::vector<int> all;
bool each_producer_in_order = true;
for (const auto& mine : received) {
all.insert(all.end(), mine.begin(), mine.end()); // gather every item
// For this consumer: the last item it saw from each producer.
// Each producer's items must keep increasing.
std::vector<int> last(producers, -1);
for (const int item : mine) {
const int p = item / per_producer;
each_producer_in_order = each_producer_in_order && item > last[p];
last[p] = item;
}
}
std::sort(all.begin(), all.end());
// 0, 1, 2, ..., 7999: what `all` must be once sorted.
std::vector<int> expected(producers * per_producer);
for (std::size_t i = 0; i < expected.size(); ++i) {
expected[i] = static_cast<int>(i);
}
LLD_CHECK(all == expected); // every item exactly once: none lost, none twice
LLD_CHECK(each_producer_in_order);
LLD_CHECK(queue.stats().high_water <= 8u);
}
  • Four producers and three consumers move 8,000 items through a queue with room for 8. The test collects every item the consumers received, sorts them, and checks that they are exactly 0 to 7,999: every item arrived, and none arrived twice. It also checks that each consumer saw each producer’s items in the order that producer sent them, and that the high-water mark never passed 8. Items from different producers may interleave in any way, so that is all the test can require.
  • The order of joins matters. The producers’ threads are joined first, then the queue is closed, then the consumers are joined: closing earlier would refuse items that producers were still sending.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_bounded_queue.cpp
// 8 threads each take a slot 200 times from 3 slots. Checks that no thread
// ever found more than 3 holders inside at once.
LLD_TEST(slots_never_let_more_than_their_count_in) {
flow::Slots slots(3);
std::atomic<int> inside{0};
std::atomic<int> too_many{0};
{
std::vector<std::jthread> users;
for (int t = 0; t < 8; ++t) {
users.emplace_back([&] {
for (int i = 0; i < 200; ++i) {
// The permit lives until the end of this loop pass.
const flow::Slots::Permit permit = slots.acquire();
// fetch_add returns the old count; + 1 includes this thread.
if (inside.fetch_add(1) + 1 > 3) {
too_many.fetch_add(1);
}
std::this_thread::yield();
inside.fetch_sub(1); // leaves before the permit is released
}
});
}
}
LLD_CHECK_EQ(too_many.load(), 0);
}
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// an exception of that type.
LLD_TEST(slots_refuse_a_count_below_one) {
LLD_CHECK_THROWS(flow::Slots(0), std::invalid_argument);
}
// Takes the only slot, then throws inside the permit's scope. Proves the
// slot is free again once the exception has left that scope.
LLD_TEST(a_permit_is_returned_when_an_exception_leaves_its_scope) {
flow::Slots slots(1);
try {
const flow::Slots::Permit permit = slots.acquire();
throw std::runtime_error("export failed");
} catch (const std::runtime_error&) {
} // the throw destroyed `permit` on its way here, releasing the slot
// try_acquire never waits. (The standard lets it fail now and then even
// when a slot is free, so this check could in principle fail falsely.)
auto again = slots.try_acquire();
LLD_CHECK(again.has_value());
LLD_CHECK(!slots.try_acquire().has_value()); // the only slot is taken by `again`
}
  • The semaphore’s limit: eight threads take permits from three slots 200 times each, and none ever finds more than three inside.
  • A count below one is refused with std::invalid_argument, so a misconfigured limit fails at startup instead of blocking every caller.
  • A permit survives an exception: after a throw inside the permit’s scope, the one slot is free again.

Every test also runs under the tsan preset, and ThreadSanitizer reports nothing for them. As on the earlier pages, that is evidence about the interleavings the tests produced, not proof about all of them.

class flow::BoundedQueue<T>

safe; T must be nothrow move constructible

Data members

  • mutable std::mutex mutex_;
  • std::condition_variable not_full_; producers wait here
  • std::condition_variable not_empty_; consumers wait here
  • std::deque<T> items_; guarded by mutex_
  • bool closed_; guarded by mutex_
  • QueueStats stats_; guarded by mutex_
  • const std::size_t capacity_;
  • const WhenFull policy_;

Member functions

  • BoundedQueue(std::size_t capacity, WhenFull policy); throws std::invalid_argument for 0
  • PushResult push(T item); nodiscard; waits only under WhenFull::block
  • std::optional<T> pop(); waits; nullopt only once closed and empty
  • void close(); refuse new items, wake every waiter
  • QueueStats stats() const; a consistent copy
  • std::size_t capacity() const noexcept;

class flow::Slots

safe; a fixed number of permits

Data members

  • std::counting_semaphore<> free_;

Member functions

  • explicit Slots(std::ptrdiff_t count); throws std::invalid_argument unless 1 <= count <= max()
  • Permit acquire(); nodiscard; waits for a free slot
  • std::optional<Permit> try_acquire(); nodiscard; nullopt if none is free, rarely even if one is

class flow::Slots::Permit

move only; releases its slot when destroyed

Data members

  • Slots* slots_; null after a move

struct flow::QueueStats

a value

Member functions

  • std::size_t size;
  • std::size_t high_water;
  • std::size_t dropped;
  • std::size_t rejected;

class flow::CloseOnExit<T>

closes the queue when destroyed; not copyable

Data members

  • BoundedQueue<T>* queue_;

Member functions

  • explicit CloseOnExit(BoundedQueue<T>& queue) noexcept;
A bounded queue with one overflow policy, and RAII permits over a counting semaphore

When this design fits, and when it does not

Section titled “When this design fits, and when it does not”

A bounded queue with a chosen policy fits when:

  • Producers and consumers run at different speeds, at least for a while, and memory must stay bounded (Q4).
  • The cost of overload has an obvious place to land: on producers that can wait, on callers that can be told no, or on items that can be lost.
  • Work moves in one direction, from producers to consumers, with no answer expected on the same path.

Something else fits better when:

  • The producer needs the answer before it continues. Then it is a function call, perhaps on another thread with a future, as on the previous page; a queue adds delay and nothing else.
  • The limit is on simultaneous use, not on waiting work. Use permits, as in Slots.
  • One thread does everything. If one thread both produces and consumes, a blocking queue can wait for itself. A plain container is enough.
  • The capacity cannot be chosen. A bound must come from something: memory per item, how long an item may wait before it is useless, or how large a burst must be absorbed. A number picked without a reason will be wrong, and should be measured, made configurable, and reported (Q5). A first estimate comes from the arrival rate and the longest acceptable wait: at 800 items a second, a wait of at most half a second means about 400 items queued (800 × 0.5). A count is not a memory bound when item sizes vary; then bound the bytes, or the size of each item, as well.
  • An unbounded queue between threads of different speeds. The overload is hidden until memory runs out.
  • Blocking a thread that must not block, such as a thread that answers users or holds a lock that others need. Use reject there.
  • Dropping items silently. Count drops and rejections, and report them; an overload no one can see will not be fixed.
  • One condition variable for “not full” and “not empty”, with notify_one. It can wake the wrong side.
  • A consumer that stops at the first empty queue. Empty does not mean finished; only closed and empty does.
  • Closing the queue before every producer has stopped. Late items are refused, and under the block policy they were items that must not be lost.
  • A semaphore without RAII. One early return or exception leaks a permit, and the limit quietly shrinks.
  • Closing only on the success path. If a producer throws before it calls close, the consumers wait forever and joining them hangs. Close from a destructor, as CloseOnExit does.
  • A cycle of blocking queues. If thread A pushes into a queue that thread B drains, and B pushes into a queue that A drains, both queues can fill while each thread waits for the other. That is a deadlock. Break the cycle, or make one direction reject instead of block.
  • “Wait for room, but not for more than 50 milliseconds.” Add a push_for(item, timeout) that uses not_full_.wait_for with the same predicate, and returns rejected if the time runs out. It is the block and reject policies combined.
  • “A burst of 10,000 items at startup is normal.” Either raise the capacity to absorb the burst, if memory allows, or let the producer wait during startup only. The choice depends on whether the burst is worth its memory, not on the queue.
  • “Audit events from administrators must never wait behind others.” Two queues, or a queue with priorities. Decide what happens to the low-priority items when high-priority ones never stop, or they may starve.
  • “Write audit events in batches of 100.” Add a pop_up_to(n) that waits for at least one item and returns as many as are there, up to n, so the consumer pays for one write per batch. Taking several items frees several places, so it must wake producers with notify_all, or with one notify_one per item taken; a single notify_one would leave the other waiting producers asleep.
  • “The export service now allows five connections, set by configuration.” Slots takes its count at construction, so the composition root reads the setting. A count that must change while the program runs needs a different design.

Exercise: Choose a policy per scenario

For each scenario, choose block, reject, drop oldest, or a semaphore (permits for simultaneous use), and say why. Then say what would change your answer.

  1. A payment service puts every completed payment on a queue for the thread that writes the accounting ledger.
  2. A map shows the positions of delivery vans. Each van sends its position every second.
  3. A web form asks for a PDF report to be generated. Generating one takes about 20 seconds.
  4. A request handler writes debug log lines to a queue for a logging thread. Requests must never slow down because of logging.
  5. A program calls a partner’s API, whose contract allows at most four requests in flight at once from each customer. All of this program’s calls are made for one customer.
Show the explained answer

1. Block. A lost payment record is a lost record of money, so nothing may be dropped or refused silently. The producer can wait: the payment has already been made, and recording it a little later is acceptable. What would change it: if the producer is the thread answering the customer, waiting there makes customers wait for the ledger writer. Then reject with a durable fallback (write the record to local storage and retry later), and treat any rejection as an alarm. And if a record must survive a crash, no in-memory queue is enough; the record must be stored before the payment is confirmed.

2. Drop oldest, and better still, one slot per van. Only the latest position of each van matters; a position from ten seconds ago is worse than none. With one shared queue, a van that sends too often can push every other van’s latest position out; one slot per van, where a new position replaces that van’s old one, keeps every van on the map. What would change it: if the positions are also used to bill distance driven, then every position matters, and that use needs its own queue with the block policy.

3. Reject. The user is waiting for an answer, and “the report queue is full, try again in a minute” is better than a page that hangs for minutes. A small capacity, for example the number of reports that can be generated in a minute or two, keeps the wait honest. What would change it: if reports are emailed instead of shown, the user is not waiting, and the request can be accepted into durable storage instead.

4. Drop, with a count. Debug lines are worth less than the requests that produce them. Dropping the oldest keeps the most recent context, which is usually the useful part when something goes wrong; dropping the newest is cheaper and also acceptable. Either way, count the drops and log the count, so a gap in the log is explained. Dropping still takes the queue’s mutex for a moment, so “never slow down” means “never wait for the logging thread”, not “cost nothing”. What would change it: audit or security logs are not debug logs; they need the block policy, or storage that cannot fall behind.

5. A semaphore with four permits, wrapped in an RAII permit as Slots does. The limit is on simultaneous use, not on waiting work. Whether a caller waits for a permit (acquire) or gives up (try_acquire) is a separate choice, made the same way as above: can the caller wait? What would change it: if the program needs one long-lived connection per request slot, it is a pool of connection objects, not just a count.

  • A queue between threads of different speeds needs a limit, or overload shows up late, as memory exhaustion. Backpressure makes the consumer’s slowness reach the producers.
  • When full, a queue can block, reject, or drop. Each puts the cost of overload somewhere: on the producer’s time, on its caller, or on the data. Choose per kind of item.
  • Write the producer and consumer contracts in the header: when push waits, and what the end of the stream looks like.
  • Closing the queue is the shutdown signal: producers stop, the queue closes, consumers drain, then they are joined.
  • Make overflow visible: a high-water mark and counts of drops and rejections.
  • For a limit on simultaneous use, use std::counting_semaphore, always through an RAII permit.