Unit 6 of 9 · about 4 hours · implement
Bounded queues, admission and backpressure
Programming's backpressure unit built admission with asyncio.Queue. This unit rebuilds it in C with explicit invariants, close states and a measured drain, which is the piece the fault-tested service slice reuses. It assumes that unit as background and never reuses its queue demo.
You'll be able to
- Implement a bounded producer-consumer queue with two condition variables and state its full and empty invariants.
- Add close semantics that drain admitted items, reject late puts and wake every waiter.
- Derive queued-memory and worst-wait bounds from capacity, item size, service rate and worker count.
Covers
Read
In this order, only the parts listed
0 of 6 done
- Producer and consumer with condition variablesOperating Systems: Three Easy Pieces - concurrency
Section 30.2 with the two-condition-variable while version as the reference implementation
- Bounded buffer with semaphores, plus throttlingOperating Systems: Three Easy Pieces - concurrency
Sections 31.4 and 31.7: counting semaphores as fill and empty counts, and thread throttling as admission
- Concurrent queuesOperating Systems: Three Easy Pieces - concurrency
Section 29.3: the concurrent queue structure and where the locks live
- Producer-Consumer PatternAlgoMaster Concurrency lessons
Core Components; Implementation; When to Use / When Not to Use
- Bounded BufferAlgoMaster Concurrency lessons
Solution 2: Semaphore-Based Solution; Solution 3: Monitor-Based Solution; Solution Comparison
Compare the two solutions; skip the naive busy-waiting variant except as a failure example.
- Design Thread-Safe Blocking QueueAlgoMaster Concurrency lessons
Approach 1: Single Lock with Conditions; Approach 2: Two-Lock Queue; Solution Comparison
Focus on
- Two predicates, two condition variables: not-full for producers, not-empty for consumers. One CV forces broadcast-on-every-op or risks a stolen signal.
- Capacity bounds memory and wait: max queued bytes equal capacity times item size, and a newly admitted item waits at most capacity divided by aggregate service rate, plus one service time. State units with every bound.
- Close is a state, not a signal:
CLOSEDrejects puts, preserves admitted items in FIFO order and wakes all waiters. A bare broadcast without the flag re-sleeps or loses items. - Admission control turns overload into explicit rejection: the rate limiter allows at most
limitpermits per aligned window, with lookup, reset, check and increment as one atomic operation.
Common mistakes · 3
notify_oneagainstnotify_allis a correctness choice under close: waking one consumer while producers also wait can stall shutdown. Broadcast on close.- Window edges admit bursts: a fixed-window limiter allows
limitpermits at the end of one window andlimitmore at the start of the next. Name the factor of 2 before claiming smoothness. - An unbounded queue plus a slow consumer is a memory leak with a polite name. Bound the queue or bound the wait; bound both when the slice demands it.
Try it yourself
Closed-book, before checking anything
-O2 -pthread (capacity 4): 2 producers times 5000 items with 2 consumers must drain exactly 10000 over three runs, post-close put must return -1, take on the drained closed queue must return -1, and the -fsanitize=thread build must be clean. State CPU, kernel, compiler, flags and repeats.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why two condition variables instead of one?Answer
Producers and consumers wait for different predicates. With one CV a producer signal can wake another producer, which re-sleeps while consumers stay asleep. At close, broadcast wakes everyone and each re-checks its own predicate.
2.Capacity 1000, 8-byte items, 2 workers each serving 50000 items/s. Bound the queued memory and the worst wait of an admitted item.Answer
Memory: 1000 times 8 = 8000 bytes plus bookkeeping. Wait: at most 1000 items ahead drain at 100000/s, about 10 ms, plus one 20 us service time.
3.Close arrives with 3 items queued and 1 producer blocked in
put. What must happen?AnswerThe blocked
putwakes and fails without adding. The 3 items drain in FIFO order. Takes after drain report closed, and later puts fail immediately.4.Why must the window check, reset,
limitcheck and increment be one atomic operation?AnswerOtherwise two threads in the same window both observe a count below
limitand both consume the last permit, admittinglimitplus 1.
Practice
- AlgoMaster: Design a Closable Bounded Queue
put,takeandclosewith the five stated rules (drain in FIFO order, blocked puts fail, takes report no-item when drained); the judge runs concurrent producers, consumers and closersYour C queue is the reference; now satisfy the judge's in-browser contract.
- AlgoMaster: Design Thread-Safe Rate Limiter
Fixed aligned windows with at most
limitpermits per client per window; window lookup, reset, check and increment as one atomic operation under the judge's logical clockUse the supplied logical clock, never the system clock.
You're done when
Your C queue drains 10000 of 10000 under TSan, both judges pass, and you can derive the memory and wait bounds for a new capacity.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 7 more in the section
- Operating Systems: Three Easy Pieces - concurrencyRemzi and Andrea Arpaci-Dusseau · primary
Read Chapters 26-33 in order: threads, thread API, locks, locked data structures, condition variables, semaphores, bugs and event-based concurrency. Write the safety and liveness invariant before reading each worked pattern.
- AlgoMaster Concurrency lessonsAlgoMaster · support
Use the named lessons only: Processes vs Threads, Race Conditions and Critical Sections, Mutex, Condition Variables, Compare-And-Swap, Atomic Operations, Semaphores, Producer-Consumer Pattern, Bounded Buffer, Design Thread-Safe Blocking Queue, Barriers and Latches, Read-Write Locks, Coarse-grained vs Fine-grained Locking, Deadlock, Livelock, Starvation, Priority Inversion, Lost Signal/Wakeup, Spurious Wakeup, Concurrency Models and Thread Pool Pattern. Each unit names its lessons; read no other chapter for this section.
Also in this section
- OSTEP concurrency homework and codeOSTEP authors · required
Use x86.py and the main, vector, condition-variable and semaphore exercises to enumerate schedules. Preserve one lost update, one deadlock and one lost wakeup as minimized tests, then repair each invariant.
- AlgoMaster Concurrency - four bounded contractsAlgoMaster · required
Attempt Design a Closable Bounded Queue, Design Thread-Safe Rate Limiter, Design a Deadlock-Free Two-Key Executor, Design an Atomic Maximum With Compare-and-Swap, Design Deferred Callback Executor and Design Task Scheduler with Dependencies. For each, add a changed input, a deterministic failure schedule and an independent stress test outside the platform.
- MIT 6.1810 - locks and parallelismMIT PDOS · depth
Use Lectures 12-14 and one lock-lab exercise only after the user-space bounded queue passes. Measure the contention change and explain the invariant preserved by the revised locking scheme.
- Linux man-pages: pthreads and futexLinux man-pages project · reference
Look up the exact pthread mutex, condition variable, barrier, cancellation and timed-wait contracts plus futex(2) and pthreads(7). Read the stated pages; do not browse the whole manual.
- cppreference: C atomic operationscppreference · reference
Read
atomic_compare_exchangefor success and failure semantics and the expected-pointer update rule, andmemory_orderfor the six orderings and what relaxed permits. Stop before lock-free-property macros. - GCC __atomic builtinsGNU Compiler Collection · reference
Read
__atomic_compare_exchange,__atomic_loadand__atomic_storefor the expected-pointer update rule and the__ATOMIC_RELAXEDconstant used by the CAS reproduce step. - The Little Book of SemaphoresGreen Tea Press · support
Use the rendezvous, barrier and reader-writer puzzles as extra semaphore practice after OSTEP Chapter 31. Skip the Python event material; this section works in C with pthreads.