1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#![allow(clippy::mutex_atomic)]

//! A library that makes signaling between threads a bit more ergonomic
//! than using a `CondVar` + `Mutex` directly.
//!
//! # Examples
//!
//! ```rust
//! use std::thread;
//!
//! let (signaler, listener) = waithandle::new();
//!
//! let thread = thread::spawn({
//!     move || {
//!         while !listener.check().unwrap() {
//!             println!("Doing some work...");
//!             if listener.wait(Duration::from_secs(1)).unwrap() {
//!                 println!("Someone told us to exit!");
//!                 break;
//!             }
//!         }
//!     }
//! });
//!
//! thread::sleep(Duration::from_secs(5));
//!
//! println!("Signaling thread...");
//! signaler.signal().unwrap();
//! println!("Joining thread...");
//! thread.join().unwrap();
//! ```

use std::error;
use std::fmt;
use std::fmt::Formatter;
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::time::Duration;

/// The result of a wait handle operation.
pub type WaitHandleResult<T> = std::result::Result<T, WaitHandleError>;

///////////////////////////////////////////////////////////
// Constructor

/// Creates a wait handle pair for signaling and listening.
pub fn new() -> (WaitHandleSignaler, WaitHandleListener) {
    let wait_handle = Arc::new(WaitHandle::new());
    let signaler = WaitHandleSignaler::new(wait_handle.clone());
    let listener = WaitHandleListener::new(wait_handle);
    (signaler, listener)
}

///////////////////////////////////////////////////////////
// Wait handle

#[derive(Debug, Default)]
struct WaitHandle {
    pair: Arc<(Mutex<bool>, Condvar)>,
}

impl WaitHandle {
    /// Creates a new wait handle.
    pub fn new() -> Self {
        let pair = Arc::new((Mutex::new(false), Condvar::new()));
        return WaitHandle { pair };
    }

    pub fn check(&self) -> WaitHandleResult<bool> {
        self.wait(Duration::from_micros(0))
    }

    pub fn wait(&self, timeout: Duration) -> WaitHandleResult<bool> {
        let (lock, cvar) = &*self.pair;
        let mut guard = lock.lock()?;
        let result = cvar.wait_timeout_while(guard, timeout, |&mut pending| !pending)?;
        guard = result.0;
        if *guard {
            return Ok(true);
        }
        Ok(false)
    }

    pub fn reset(&self) -> WaitHandleResult<()> {
        self.set(false)
    }

    pub fn signal(&self) -> WaitHandleResult<()> {
        self.set(true)
    }

    fn set(&self, value: bool) -> WaitHandleResult<()> {
        let (lock, cvar) = &*self.pair;
        let mut guard = lock.lock()?;
        if *guard != value {
            *guard = value;
            cvar.notify_one();
        }
        Ok(())
    }
}

///////////////////////////////////////////////////////////
// Signaler

/// The signaling half of a wait handle.
#[derive(Clone)]
pub struct WaitHandleSignaler {
    handle: Arc<WaitHandle>,
}

impl WaitHandleSignaler {
    fn new(handle: Arc<WaitHandle>) -> Self {
        Self { handle }
    }

    pub fn reset(&self) -> WaitHandleResult<()> {
        self.handle.reset()
    }

    pub fn signal(&self) -> WaitHandleResult<()> {
        self.handle.signal()
    }
}

///////////////////////////////////////////////////////////
// Listener

/// The listening half of a wait handle.
#[derive(Clone)]
pub struct WaitHandleListener {
    handle: Arc<WaitHandle>,
}

impl WaitHandleListener {
    fn new(handle: Arc<WaitHandle>) -> Self {
        Self { handle }
    }

    pub fn check(&self) -> WaitHandleResult<bool> {
        self.handle.check()
    }

    pub fn wait(&self, timeout: Duration) -> WaitHandleResult<bool> {
        self.handle.wait(timeout)
    }
}

///////////////////////////////////////////////////////////
// Errors

/// Represents a wait handle error.
#[derive(Debug, Clone)]
pub enum WaitHandleError {
    LockPoisoned,
}

impl fmt::Display for WaitHandleError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            WaitHandleError::LockPoisoned => write!(f, "wait handle lock poisoned"),
        }
    }
}

impl error::Error for WaitHandleError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        None
    }
}

impl<T> From<PoisonError<T>> for WaitHandleError {
    fn from(_: PoisonError<T>) -> Self {
        WaitHandleError::LockPoisoned
    }
}