std: fix deadlock in Parker

This commit is contained in:
joboet 2022-05-19 14:37:29 +02:00
parent fd76552a4b
commit 3b6ae15058
No known key found for this signature in database
GPG Key ID: 704E0149B0194B3C
2 changed files with 13 additions and 8 deletions

View File

@ -42,13 +42,18 @@ pub fn wait(&self) {
}
/// Wait for the wait flag to be raised or the timeout to occur.
pub fn wait_timeout(&self, dur: Duration) {
///
/// 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 er = with_tmos(dur, |tmout| unsafe {
let res = with_tmos(dur, |tmout| unsafe {
abi::twai_flg(self.flag, RAISED, abi::TWF_ORW, token.as_mut_ptr(), tmout)
});
if er != abi::E_OK && er != abi::E_TMOUT {
fail(er, &"twai_flg");
match res {
abi::E_OK => true,
abi::E_TMOUT => false,
error => fail(error, &"twai_flg"),
}
}

View File

@ -2,7 +2,7 @@
//!
//! 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 occure before the wait operation). To implement the `std` thread
//! 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.
@ -73,10 +73,10 @@ pub unsafe fn park_timeout(self: Pin<&Self>, dur: Duration) {
_ => panic!("inconsistent park state"),
}
self.wait_flag.wait_timeout(dur);
let wakeup = self.wait_flag.wait_timeout(dur);
let state = self.state.swap(EMPTY, SeqCst);
if state == NOTIFIED {
// The token was made available after the timeout occurred, but before
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