Read-Write Lock - Problem

Implement a read-write lock that allows multiple concurrent readers but exclusive writers. The lock should provide the following functionality:

Reader Lock: Multiple threads can acquire reader locks simultaneously as long as no writer lock is held

Writer Lock: Only one thread can acquire a writer lock, and no reader locks can be held while a writer lock is active

Fair Scheduling: Prevent writer starvation by ensuring waiting writers get priority over new readers

Your implementation should handle concurrent access from multiple threads and provide acquire_read(), release_read(), acquire_write(), and release_write() methods.

Input & Output

Example 1 — Basic Read-Write Operations
$ Input: operations = ["acquire_read", "acquire_read", "acquire_write", "release_read", "release_read"]
Output: [true,true,false,true,true]
💡 Note: Two readers acquire successfully, writer fails due to active readers, then readers release successfully
Example 2 — Writer Priority
$ Input: operations = ["acquire_write", "acquire_read", "release_write", "acquire_read"]
Output: [true,false,true,true]
💡 Note: Writer acquires exclusively, reader blocked, writer releases, then reader can acquire
Example 3 — Multiple Operations
$ Input: operations = ["acquire_read", "acquire_read", "release_read", "acquire_write", "release_read", "release_write"]
Output: [true,true,true,false,true,true]
💡 Note: Multiple readers work concurrently, writer waits for all readers to finish

Constraints

  • 1 ≤ operations.length ≤ 1000
  • operations[i] is one of "acquire_read", "release_read", "acquire_write", "release_write"
  • Each release operation has a corresponding acquire operation
  • No more than 100 concurrent readers or writers

Visualization

Tap to expand
INPUTLock Operation Sequenceacquire_read, acquire_readacquire_writerelease_read, release_readMultiple concurrent operationsneed coordination mechanismALGORITHMFair Read-Write Lock Steps1Check lock state and priorities2Update reader count or writer flag3Grant or deny access4Apply fairness policyState Variablesreaders = 2writer_active = falsewriter_priority = trueRESULTOperation ResultsReaders: [true, true]Concurrent access grantedWriter: [false]Blocked by active readersReleases: [true, true]Successful cleanupFinal: [true,true,false,true,true]Key Insight:Separate reader counters and writer priority flags enable maximum concurrencywhile preventing writer starvation through fair scheduling policies.TutorialsPoint - Read-Write Lock | Fair Priority Queue Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
31.2K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen