use ::core::time::Duration;
use std::sync::{Arc, Condvar, Mutex};
use crate::prelude::*;
pub struct ThreadWaitBarrier {
mtx: std::sync::Mutex<u32>,
cv: std::sync::Condvar,
ntf_cnt: FoundationAtomicU32,
expected_cnt: u32,
}
pub struct ThreadReadyNotifier {
inner: Arc<ThreadWaitBarrier>,
}
impl ThreadReadyNotifier {
pub fn ready(self) {
{
let mut value = self.inner.mtx.lock().unwrap();
*value -= 1;
}
self.inner.cv.notify_one();
}
}
impl ThreadWaitBarrier {
pub fn new(thread_to_wait: u32) -> Self {
Self {
mtx: Mutex::new(thread_to_wait),
cv: Condvar::new(),
ntf_cnt: FoundationAtomicU32::new(0),
expected_cnt: thread_to_wait,
}
}
pub fn get_notifier(self: &Arc<Self>) -> Option<ThreadReadyNotifier> {
let new_cnt = self
.ntf_cnt
.fetch_update(
::core::sync::atomic::Ordering::SeqCst,
::core::sync::atomic::Ordering::SeqCst,
|current| {
if current >= self.expected_cnt {
None
} else {
Some(current + 1)
}
},
)
.unwrap_or_else(|e| e);
if new_cnt >= self.expected_cnt {
None
} else {
Some(ThreadReadyNotifier { inner: self.clone() })
}
}
pub fn wait_for_all(&self, dur: Duration) -> Result<(), CommonErrors> {
let res = self.cv.wait_timeout_while(self.mtx.lock().unwrap(), dur, |cond| *cond > 0).unwrap();
if res.1.timed_out() {
Err(CommonErrors::Timeout)
} else {
Ok(())
}
}
}
#[cfg(test)]
#[cfg(not(loom))]
mod tests {
use super::*;
use ::core::time::Duration;
use std::sync::Arc;
use std::thread;
#[test]
fn test_thread_wait_barrier_all_threads_ready() {
let barrier = Arc::new(ThreadWaitBarrier::new(3));
let mut handles = vec![];
for _ in 0..3 {
let notifier = barrier.get_notifier().unwrap();
handles.push(thread::spawn(move || {
thread::sleep(Duration::from_millis(100));
notifier.ready();
}));
}
assert!(barrier.wait_for_all(Duration::from_secs(1)).is_ok());
for handle in handles {
handle.join().unwrap();
}
}
#[test]
fn test_thread_wait_barrier_timeout() {
let barrier = Arc::new(ThreadWaitBarrier::new(3));
let notifier = barrier.get_notifier().unwrap();
let handle = thread::spawn(move || {
thread::sleep(Duration::from_millis(500));
notifier.ready();
});
assert!(barrier.wait_for_all(Duration::from_millis(100)).is_err());
handle.join().unwrap();
}
#[test]
fn test_thread_wait_barrier_exceed_notifiers() {
let barrier = Arc::new(ThreadWaitBarrier::new(2));
let notifier1 = barrier.get_notifier().unwrap();
let notifier2 = barrier.get_notifier().unwrap();
let extra_notifier = barrier.get_notifier();
assert!(extra_notifier.is_none());
notifier1.ready();
notifier2.ready();
assert!(barrier.wait_for_all(Duration::from_secs(1)).is_ok());
}
}