-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Write guard to read guard downgrading for sync::RwLock #2733
Conversation
/// Atomically downgrades a write lock into a read lock without allowing | ||
/// any writers to take exclusive access of the lock in the meantime. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, because Tokio's locks are fairly queued, if the next queued waiter is a writer, no additional waiters will be allowed access. I'm not sure if that behavior is actually an issue, or not, but it's worth noting.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's the same behavior as if the holder of the (to be downgraded) write guard had initially acquired a read guard instead. It might not always be ideal, but it's the behavior required to avoid starving writers. I'll add a note.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
looks good to me — @carllerche may want to sign off, since this adds a new public API function.
@hawkw I'm OK w/ this 👍 merge whenever it is ready. |
Co-authored-by: Alice Ryhl <alice@ryhl.io>
f7e2ff0
to
431a1ef
Compare
@hawkw rebased onto master and fixed things up |
Motivation
The asynchronous
sync::RwLock
currently provides no way to atomically downgrade a write guard into a read guard, forcing a pattern of dropping the write guard and reacquiring a read guard to achieve a downgrade. In addition to being non-atomic, this makes it easy to accidentally induce a deadlock by forgetting to drop an existing read guard before attempting to acquire a write guard--this is particularly tricky and non-obvious when shadowing the name of the old read guard.Solution
This implements an atomic downgrade operation by taking ownership of a write guard, releasing all but one of the permits it holds, and returning a read guard holding the remaining permit.