Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Pull Request check-list
Please make sure to review and check all of these items:
NOTE: these things are not required to open a PR and can be done
afterwards / while the PR is open.
Description of change
This implements the reader-write lock requested in #2372. It is a pretty sizeable standalone feature that may take a while to review.
The interface and implementation I think are explained decently well in docstrings and comments. Briefly: the lock state is stored in three keys:
<prefix>:write
: Standard mutex lease<prefix>:write_semaphore
: Semaphore that tracks waiting writers, implemented as an ordered set.<prefix>:read
: Semaphore that tracks readers.I tried to keep the interface (and implementation) similar to the existing
Lock
class while taking inspiration from the Rust and C++ standard libraries for the new bits. I got rid of thread-local state since each read/write guard now generates its own token.Other than supporting multiple readers, the only really "new" feature is the
max_writers
parameter, which can be used to cap the number of waiting writers. Typically I expect most users would only choose 0/None (unlimited) or 1 (guarantee single writer).Benchmark
I included a benchmark that simulates a group of workers sharing the lock for reading and writing. Perhaps it doesn't measure numbers that are super meaningful to optimize, but it shows that the lock demonstrates the expected behavior, and you can run parameter sweeps to see how it handles different levels of contention.
I added dev dependencies on pandas (for printing stats) and matplotlib (for reproducing graphs). matplotlib is not needed to run the benchmark, only to visualize the time series output after a run.
Sample run output