Design a synchronization primitive that coordinates read-only and write callbacks around a shared resource.
Implement the ReadWriteCoordinator class:
read(readTask) waits for read access and then invokes readTask exactly once.write(writeTask) waits for write access and then invokes writeTask exactly once.
Any number of read callbacks may execute simultaneously. A write callback must execute alone: it cannot overlap another writer or any reader using the same coordinator.
Access lasts for the callback's entire execution. If a callback throws an unchecked exception or panics, the corresponding access must still be released and the original failure must continue to the caller.
Different ReadWriteCoordinator instances must be independent. No particular fairness policy or reader/writer ordering is required.
The judge creates all caller threads and supplies the callbacks. Standard concurrency, callback, read-write-lock, and thread APIs are preloaded, so you do not need import, include, package, or using statements.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Explanation: The order between writeA and readB is unspecified, but a writer always has exclusive access while its callback is running.
Constraints
- At most
100 threads use one coordinator at a time. - At most
50000 total calls are made per instance. - A callback may complete normally or fail with an unchecked exception or panic.
- Callbacks do not recursively call
read or write on the same coordinator. - Judge threads are not interrupted while waiting for access.