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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code