A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Readers-Writers Problem and Lock Patterns

College Depth 107 in the knowledge graph I know this Set as goal
415prerequisites beneath it
See this on the map →
Monitors and Condition VariablesProducer-Consumer Problem: Classic Synchronization
synchronization-patterns fairness reader-writer-locks

Core Idea

The readers-writers problem allows multiple readers concurrently but requires exclusive access for writers. Simple solutions risk starving one group. Reader-preference solutions favor readers; writer-preference favor writers. Fair solutions prevent starvation via condition variables tracking reader/writer counts.

Common Misconceptions

Any solution works (reader-preference starves writers; writer-preference starves readers). Readers never conflict (they do; writes require exclusive access).

Explainer

The readers-writers problem captures a pattern that appears constantly in real systems: many threads need to read shared data, but occasionally one thread needs to update it. A simple mutex would work — lock before access, unlock after — but it would force readers to wait for each other even though simultaneous reads are perfectly safe. The whole point of the readers-writers problem is to allow concurrent reads while still guaranteeing exclusive writes. Since you already understand condition variables and monitors, you have the tools to build solutions; the challenge is choosing *which* solution and understanding its fairness tradeoffs.

The simplest approach is reader-preference: readers can always enter as long as no writer is active. A shared counter tracks the number of active readers. The first reader to arrive locks out writers; the last reader to leave unlocks the resource. Writers must wait until the reader count drops to zero. This maximizes read throughput, but if readers arrive continuously, a writer may wait forever — this is writer starvation. In a system where reads vastly outnumber writes and write latency is not critical, this tradeoff might be acceptable, but in general it is dangerous.

The mirror image is writer-preference: when a writer is waiting, no new readers are admitted. Arriving readers queue behind the pending writer. This guarantees writers make progress but can starve readers if writes are frequent. The solution uses a condition variable for waiting readers and a separate one for waiting writers, with the monitor deciding whom to wake. You can think of it as a priority system: writers jump the queue ahead of new readers, though currently-active readers are allowed to finish.

A fair solution prevents starvation for both sides. One common approach uses a turnstile — a semaphore or condition variable that writers lock when they arrive, forcing subsequent readers to queue behind the writer in arrival order. Once the writer finishes, the queued readers are released together and can read concurrently until the next writer arrives. Another fair approach uses a single FIFO queue where readers and writers are served in order of arrival, with consecutive readers batched together. The key insight is that fairness requires tracking arrival order, not just counts. When implementing these patterns, the condition variable predicates from your prerequisite knowledge — "wait while the condition is not met, re-check after being signaled" — are exactly the mechanism that makes each variant work.

Practice Questions 5 questions

Prerequisite Chain

Understanding ZeroThe Number ZeroCounting to FiveCounting to 10Counting to 20Counting a Set of Objects Up to 20Cardinality: The Last Number CountedMatching Numerals to QuantitiesSubitizing Small QuantitiesAddition Within 10Number Bonds to 10Addition Within 20Doubles and Near DoublesDoubles Facts Within 10Near Doubles Facts Within 20Mental Math Strategies for AdditionMental Math: Adding and Subtracting TensAddition Within 100Repeated Addition as MultiplicationMultiplication as Equal GroupsMultiplication: ArraysBasic Multiplication Facts (0s, 1s, 2s, 5s, 10s)Multiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Multiplication and Division Fact FamiliesRelationship Between Multiplication and DivisionDivision Facts as Inverse of MultiplicationRemainders and Quotients in DivisionDivision Word ProblemsMulti-Step Word ProblemsSolving Multi-Step Word ProblemsMultiplication Word ProblemsDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueIntegers and the Number LineComparing and Ordering IntegersAbsolute ValueAdding IntegersSubtracting IntegersMultiplying IntegersIntroduction to ExponentsOrder of OperationsInteger Order of OperationsVariable ExpressionsThe Distributive PropertyVariables and Expressions ReviewIntroduction to PolynomialsAdding and Subtracting PolynomialsMultiplying PolynomialsFactorialPermutationsCombinationsCounting Principles: Addition and Multiplication RulesIntroduction to Graph TheoryPropositional Logic FoundationsLogical EquivalencesBoolean AlgebraBoolean Type and Truth ValuesComparison Operators and Boolean TestsLogical Operators and Boolean AlgebraBoolean Algebra and Fundamental LawsLogic Gates FundamentalsImplementing Boolean Functions with GatesKarnaugh Map SimplificationCombinational Circuit DesignFlip-Flops and LatchesBinary Counters: Design and AnalysisBinary ArithmeticFixed-Point Number RepresentationTwo's Complement RepresentationOverflow and Underflow DetectionBinary Adders: Half-Adders and Full-AddersFull Adder and Carry PropagationCarry Lookahead Adder DesignHalf Adder Circuit DesignMultiplication Circuit DesignSequential Circuit DesignRegisters and Register FilesInstruction Set Architecture (ISA)Kernel Architecture and OS StructureSystem Calls and User/Kernel ModeProcesses and the Process Control BlockProcess Creation: fork() and exec()Process Termination and Resource CleanupProcess States and State TransitionsProcess Model FormalizationContext Switching and CPU DispatchCPU Scheduling FundamentalsRound-Robin (RR) SchedulingFirst-Come-First-Served (FCFS) SchedulingScheduling Fairness and Starvation PreventionThread Scheduling and CoordinationSemaphoresCounting Semaphores and Resource PoolsProducer-Consumer Problem: Classic SynchronizationReaders-Writers Problem and Lock Patterns

Longest path: 108 steps · 415 total prerequisite topics

Prerequisites (2)

Leads To (0)

No topics depend on this one yet.