Skip to content
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

sync: preserve permit state in notify_waiters #3660

Merged
merged 3 commits into from
May 5, 2021

Conversation

simonlindholm
Copy link
Contributor

Motivation

When there are no current waiters (state is EMPTY or NOTIFIED), Notify::notify_waiters just bumps the current generation counter and returns. But it does so non-atomically. Since the lock is held we know that the generation counter is untouched, and we cannot have entered state WAITING; we might however be overwriting NOTIFIED by EMPTY or EMPTY by NOTIFIED if we race with another thread.

The former case is bad: if notify_waiters() races with notify_one(), we might overwrite NOTIFIED by EMPTY and drop a permit.

The latter case is more or less fine, because if we race with a waiter that uses up a permit we can claim to have notified it and have its permit remain. But with enough effort one can show an API contract violation.

Solution

Use an atomic increment.

@Darksonn Darksonn added A-tokio Area: The main tokio crate M-sync Module: tokio/sync labels Mar 29, 2021
Copy link
Contributor

@zaharidichev zaharidichev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice find, have you tried using loom to surface the problem

@simonlindholm
Copy link
Contributor Author

Good point, that manages to reproduce the bug.

Copy link
Contributor

@Darksonn Darksonn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.

@Darksonn Darksonn merged commit 6845a93 into tokio-rs:master May 5, 2021
@Darksonn Darksonn mentioned this pull request May 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-tokio Area: The main tokio crate M-sync Module: tokio/sync
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants