Files
rust/library/std/src/sync/mpsc/blocking.rs

84 lines
2.0 KiB
Rust
Raw Normal View History

//! Generic support for building blocking abstractions.
use crate::mem;
2019-02-11 04:23:21 +09:00
use crate::sync::atomic::{AtomicBool, Ordering};
use crate::sync::Arc;
use crate::thread::{self, Thread};
2019-02-11 04:23:21 +09:00
use crate::time::Instant;
struct Inner {
thread: Thread,
woken: AtomicBool,
}
2014-12-22 00:49:42 +01:00
unsafe impl Send for Inner {}
unsafe impl Sync for Inner {}
#[derive(Clone)]
pub struct SignalToken {
inner: Arc<Inner>,
}
pub struct WaitToken {
inner: Arc<Inner>,
}
2015-01-11 11:10:04 +01:00
impl !Send for WaitToken {}
impl !Sync for WaitToken {}
pub fn tokens() -> (WaitToken, SignalToken) {
let inner = Arc::new(Inner { thread: thread::current(), woken: AtomicBool::new(false) });
let wait_token = WaitToken { inner: inner.clone() };
let signal_token = SignalToken { inner };
2015-01-11 11:10:04 +01:00
(wait_token, signal_token)
}
impl SignalToken {
2014-12-06 18:34:37 -08:00
pub fn signal(&self) -> bool {
let wake = self
.inner
.woken
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_ok();
if wake {
self.inner.thread.unpark();
}
wake
}
2019-02-09 22:16:58 +00:00
/// Converts to an unsafe usize value. Useful for storing in a pipe's state
/// flag.
#[inline]
2015-02-23 17:16:46 +13:00
pub unsafe fn cast_to_usize(self) -> usize {
mem::transmute(self.inner)
}
2019-02-09 22:16:58 +00:00
/// Converts from an unsafe usize value. Useful for retrieving a pipe's state
/// flag.
#[inline]
2015-02-23 17:16:46 +13:00
pub unsafe fn cast_from_usize(signal_ptr: usize) -> SignalToken {
SignalToken { inner: mem::transmute(signal_ptr) }
}
}
impl WaitToken {
2014-12-06 18:34:37 -08:00
pub fn wait(self) {
while !self.inner.woken.load(Ordering::SeqCst) {
2015-02-17 15:10:25 -08:00
thread::park()
}
}
2016-05-20 02:43:18 +02:00
2019-02-09 22:16:58 +00:00
/// Returns `true` if we wake up normally.
2016-05-20 02:43:18 +02:00
pub fn wait_max_until(self, end: Instant) -> bool {
while !self.inner.woken.load(Ordering::SeqCst) {
let now = Instant::now();
if now >= end {
return false;
}
thread::park_timeout(end - now)
}
true
}
}