-
Notifications
You must be signed in to change notification settings - Fork 13.4k
std: use an event-flag-based thread parker on SOLID #97140
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
use crate::mem::MaybeUninit; | ||
use crate::time::Duration; | ||
|
||
use super::{ | ||
abi, | ||
error::{expect_success, fail}, | ||
time::with_tmos, | ||
}; | ||
|
||
const CLEAR: abi::FLGPTN = 0; | ||
const RAISED: abi::FLGPTN = 1; | ||
|
||
/// A thread parking primitive that is not susceptible to race conditions, | ||
/// but provides no atomic ordering guarantees and allows only one `raise` per wait. | ||
pub struct WaitFlag { | ||
flag: abi::ID, | ||
} | ||
|
||
impl WaitFlag { | ||
/// Creates a new wait flag. | ||
pub fn new() -> WaitFlag { | ||
let flag = expect_success( | ||
unsafe { | ||
abi::acre_flg(&abi::T_CFLG { | ||
flgatr: abi::TA_FIFO | abi::TA_WSGL | abi::TA_CLR, | ||
iflgptn: CLEAR, | ||
}) | ||
}, | ||
&"acre_flg", | ||
); | ||
|
||
WaitFlag { flag } | ||
} | ||
|
||
/// Wait for the wait flag to be raised. | ||
pub fn wait(&self) { | ||
let mut token = MaybeUninit::uninit(); | ||
expect_success( | ||
unsafe { abi::wai_flg(self.flag, RAISED, abi::TWF_ORW, token.as_mut_ptr()) }, | ||
&"wai_flg", | ||
); | ||
} | ||
|
||
/// Wait for the wait flag to be raised or the timeout to occur. | ||
/// | ||
/// Returns whether the flag was raised (`true`) or the operation timed out (`false`). | ||
pub fn wait_timeout(&self, dur: Duration) -> bool { | ||
let mut token = MaybeUninit::uninit(); | ||
let res = with_tmos(dur, |tmout| unsafe { | ||
abi::twai_flg(self.flag, RAISED, abi::TWF_ORW, token.as_mut_ptr(), tmout) | ||
}); | ||
|
||
match res { | ||
abi::E_OK => true, | ||
abi::E_TMOUT => false, | ||
error => fail(error, &"twai_flg"), | ||
} | ||
} | ||
|
||
/// Raise the wait flag. | ||
/// | ||
/// Calls to this function should be balanced with the number of successful waits. | ||
pub fn raise(&self) { | ||
expect_success(unsafe { abi::set_flg(self.flag, RAISED) }, &"set_flg"); | ||
} | ||
} | ||
|
||
impl Drop for WaitFlag { | ||
fn drop(&mut self) { | ||
expect_success(unsafe { abi::del_flg(self.flag) }, &"del_flg"); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
//! A wait-flag-based thread parker. | ||
//! | ||
//! Some operating systems provide low-level parking primitives like wait counts, | ||
//! event flags or semaphores which are not susceptible to race conditions (meaning | ||
//! the wakeup can occur before the wait operation). To implement the `std` thread | ||
//! parker on top of these primitives, we only have to ensure that parking is fast | ||
//! when the thread token is available, the atomic ordering guarantees are maintained | ||
//! and spurious wakeups are minimized. | ||
//! | ||
//! To achieve this, this parker uses an atomic variable with three states: `EMPTY`, | ||
//! `PARKED` and `NOTIFIED`: | ||
//! * `EMPTY` means the token has not been made available, but the thread is not | ||
//! currently waiting on it. | ||
//! * `PARKED` means the token is not available and the thread is parked. | ||
//! * `NOTIFIED` means the token is available. | ||
//! | ||
//! `park` and `park_timeout` change the state from `EMPTY` to `PARKED` and from | ||
//! `NOTIFIED` to `EMPTY`. If the state was `NOTIFIED`, the thread was unparked and | ||
//! execution can continue without calling into the OS. If the state was `EMPTY`, | ||
//! the token is not available and the thread waits on the primitive (here called | ||
//! "wait flag"). | ||
//! | ||
//! `unpark` changes the state to `NOTIFIED`. If the state was `PARKED`, the thread | ||
//! is or will be sleeping on the wait flag, so we raise it. Only the first thread | ||
//! to call `unpark` will raise the wait flag, so spurious wakeups are avoided | ||
//! (this is especially important for semaphores). | ||
|
||
use crate::pin::Pin; | ||
use crate::sync::atomic::AtomicI8; | ||
use crate::sync::atomic::Ordering::SeqCst; | ||
use crate::sys::wait_flag::WaitFlag; | ||
use crate::time::Duration; | ||
|
||
const EMPTY: i8 = 0; | ||
const PARKED: i8 = -1; | ||
const NOTIFIED: i8 = 1; | ||
|
||
pub struct Parker { | ||
state: AtomicI8, | ||
wait_flag: WaitFlag, | ||
} | ||
|
||
impl Parker { | ||
/// Construct a parker for the current thread. The UNIX parker | ||
/// implementation requires this to happen in-place. | ||
pub unsafe fn new(parker: *mut Parker) { | ||
parker.write(Parker { state: AtomicI8::new(EMPTY), wait_flag: WaitFlag::new() }) | ||
} | ||
|
||
// This implementation doesn't require `unsafe` and `Pin`, but other implementations do. | ||
pub unsafe fn park(self: Pin<&Self>) { | ||
// The state values are chosen so that this subtraction changes | ||
// `NOTIFIED` to `EMPTY` and `EMPTY` to `PARKED`. | ||
let state = self.state.fetch_sub(1, SeqCst); | ||
match state { | ||
EMPTY => (), | ||
NOTIFIED => return, | ||
_ => panic!("inconsistent park state"), | ||
} | ||
|
||
self.wait_flag.wait(); | ||
|
||
// We need to do a load here to use `Acquire` ordering. | ||
self.state.swap(EMPTY, SeqCst); | ||
} | ||
|
||
// This implementation doesn't require `unsafe` and `Pin`, but other implementations do. | ||
pub unsafe fn park_timeout(self: Pin<&Self>, dur: Duration) { | ||
let state = self.state.fetch_sub(1, SeqCst); | ||
match state { | ||
EMPTY => (), | ||
NOTIFIED => return, | ||
_ => panic!("inconsistent park state"), | ||
} | ||
|
||
let wakeup = self.wait_flag.wait_timeout(dur); | ||
let state = self.state.swap(EMPTY, SeqCst); | ||
if state == NOTIFIED && !wakeup { | ||
// The token was made available after the wait timed out, but before | ||
// we reset the state, so we need to reset the wait flag to avoid | ||
// spurious wakeups. This wait has no timeout, but we know it will | ||
// return quickly, as the unparking thread will definitely raise the | ||
// flag if it has not already done so. | ||
self.wait_flag.wait(); | ||
} | ||
} | ||
|
||
// This implementation doesn't require `Pin`, but other implementations do. | ||
pub fn unpark(self: Pin<&Self>) { | ||
let state = self.state.swap(NOTIFIED, SeqCst); | ||
joboet marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if state == PARKED { | ||
self.wait_flag.raise(); | ||
} | ||
} | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.