1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};
14 use sync::poison::{self, LockResult};
15 use sys_common::condvar as sys;
16 use sys_common::mutex as sys_mutex;
18 use sync::{mutex, MutexGuard};
20 /// A Condition Variable
22 /// Condition variables represent the ability to block a thread such that it
23 /// consumes no CPU time while waiting for an event to occur. Condition
24 /// variables are typically associated with a boolean predicate (a condition)
25 /// and a mutex. The predicate is always verified inside of the mutex before
26 /// determining that thread must block.
28 /// Functions in this module will block the current **thread** of execution and
29 /// are bindings to system-provided condition variables where possible. Note
30 /// that this module places one additional restriction over the system condition
31 /// variables: each condvar can be used with precisely one mutex at runtime. Any
32 /// attempt to use multiple mutexes on the same condition variable will result
33 /// in a runtime panic. If this is not desired, then the unsafe primitives in
34 /// `sys` do not have this restriction but may result in undefined behavior.
39 /// use std::sync::{Arc, Mutex, Condvar};
40 /// use std::thread::Thread;
42 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
43 /// let pair2 = pair.clone();
45 /// // Inside of our lock, spawn a new thread, and then wait for it to start
46 /// Thread::spawn(move|| {
47 /// let &(ref lock, ref cvar) = &*pair2;
48 /// let mut started = lock.lock().unwrap();
50 /// cvar.notify_one();
53 /// // wait for the thread to start up
54 /// let &(ref lock, ref cvar) = &*pair;
55 /// let mut started = lock.lock().unwrap();
57 /// started = cvar.wait(started).unwrap();
61 pub struct Condvar { inner: Box<StaticCondvar> }
63 unsafe impl Send for Condvar {}
64 unsafe impl Sync for Condvar {}
66 /// Statically allocated condition variables.
68 /// This structure is identical to `Condvar` except that it is suitable for use
69 /// in static initializers for other structures.
74 /// use std::sync::{StaticCondvar, CONDVAR_INIT};
76 /// static CVAR: StaticCondvar = CONDVAR_INIT;
78 #[unstable = "may be merged with Condvar in the future"]
79 pub struct StaticCondvar {
84 unsafe impl Send for StaticCondvar {}
85 unsafe impl Sync for StaticCondvar {}
87 /// Constant initializer for a statically allocated condition variable.
88 #[unstable = "may be merged with Condvar in the future"]
89 pub const CONDVAR_INIT: StaticCondvar = StaticCondvar {
90 inner: sys::CONDVAR_INIT,
91 mutex: ATOMIC_UINT_INIT,
95 /// Creates a new condition variable which is ready to be waited on and
98 pub fn new() -> Condvar {
100 inner: box StaticCondvar {
101 inner: unsafe { sys::Condvar::new() },
102 mutex: AtomicUint::new(0),
107 /// Block the current thread until this condition variable receives a
110 /// This function will atomically unlock the mutex specified (represented by
111 /// `mutex_guard`) and block the current thread. This means that any calls
112 /// to `notify_*()` which happen logically after the mutex is unlocked are
113 /// candidates to wake this thread up. When this function call returns, the
114 /// lock specified will have been re-acquired.
116 /// Note that this function is susceptible to spurious wakeups. Condition
117 /// variables normally have a boolean predicate associated with them, and
118 /// the predicate must always be checked each time this function returns to
119 /// protect against spurious wakeups.
123 /// This function will return an error if the mutex being waited on is
124 /// poisoned when this thread re-acquires the lock. For more information,
125 /// see information about poisoning on the Mutex type.
129 /// This function will `panic!()` if it is used with more than one mutex
130 /// over time. Each condition variable is dynamically bound to exactly one
131 /// mutex to ensure defined behavior across platforms. If this functionality
132 /// is not desired, then unsafe primitives in `sys` are provided.
134 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
135 -> LockResult<MutexGuard<'a, T>> {
137 let me: &'static Condvar = &*(self as *const _);
142 /// Wait on this condition variable for a notification, timing out after a
143 /// specified duration.
145 /// The semantics of this function are equivalent to `wait()` except that
146 /// the thread will be blocked for roughly no longer than `dur`. This method
147 /// should not be used for precise timing due to anomalies such as
148 /// preemption or platform differences that may not cause the maximum amount
149 /// of time waited to be precisely `dur`.
151 /// If the wait timed out, then `false` will be returned. Otherwise if a
152 /// notification was received then `true` will be returned.
154 /// Like `wait`, the lock specified will be re-acquired when this function
155 /// returns, regardless of whether the timeout elapsed or not.
156 // Note that this method is *not* public, and this is quite intentional
157 // because we're not quite sure about the semantics of relative vs absolute
158 // durations or how the timing guarantees play into what the system APIs
159 // provide. There are also additional concerns about the unix-specific
160 // implementation which may need to be addressed.
162 fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>, dur: Duration)
163 -> LockResult<(MutexGuard<'a, T>, bool)> {
165 let me: &'static Condvar = &*(self as *const _);
166 me.inner.wait_timeout(guard, dur)
170 /// Wake up one blocked thread on this condvar.
172 /// If there is a blocked thread on this condition variable, then it will
173 /// be woken up from its call to `wait` or `wait_timeout`. Calls to
174 /// `notify_one` are not buffered in any way.
176 /// To wake up all threads, see `notify_one()`.
178 pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } }
180 /// Wake up all blocked threads on this condvar.
182 /// This method will ensure that any current waiters on the condition
183 /// variable are awoken. Calls to `notify_all()` are not buffered in any
186 /// To wake up only one thread, see `notify_one()`.
188 pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } }
191 impl Drop for Condvar {
193 unsafe { self.inner.inner.destroy() }
198 /// Block the current thread until this condition variable receives a
201 /// See `Condvar::wait`.
202 #[unstable = "may be merged with Condvar in the future"]
203 pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
204 -> LockResult<MutexGuard<'a, T>> {
205 let poisoned = unsafe {
206 let lock = mutex::guard_lock(&guard);
208 self.inner.wait(lock);
209 mutex::guard_poison(&guard).get()
212 Err(poison::new_poison_error(guard))
218 /// Wait on this condition variable for a notification, timing out after a
219 /// specified duration.
221 /// See `Condvar::wait_timeout`.
222 #[allow(dead_code)] // may want to stabilize this later, see wait_timeout above
223 fn wait_timeout<'a, T>(&'static self, guard: MutexGuard<'a, T>, dur: Duration)
224 -> LockResult<(MutexGuard<'a, T>, bool)> {
225 let (poisoned, success) = unsafe {
226 let lock = mutex::guard_lock(&guard);
228 let success = self.inner.wait_timeout(lock, dur);
229 (mutex::guard_poison(&guard).get(), success)
232 Err(poison::new_poison_error((guard, success)))
238 /// Wake up one blocked thread on this condvar.
240 /// See `Condvar::notify_one`.
241 #[unstable = "may be merged with Condvar in the future"]
242 pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
244 /// Wake up all blocked threads on this condvar.
246 /// See `Condvar::notify_all`.
247 #[unstable = "may be merged with Condvar in the future"]
248 pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
250 /// Deallocate all resources associated with this static condvar.
252 /// This method is unsafe to call as there is no guarantee that there are no
253 /// active users of the condvar, and this also doesn't prevent any future
254 /// users of the condvar. This method is required to be called to not leak
255 /// memory on all platforms.
256 #[unstable = "may be merged with Condvar in the future"]
257 pub unsafe fn destroy(&'static self) {
261 fn verify(&self, mutex: &sys_mutex::Mutex) {
262 let addr = mutex as *const _ as uint;
263 match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
264 // If we got out 0, then we have successfully bound the mutex to
268 // If we get out a value that's the same as `addr`, then someone
269 // already beat us to the punch.
272 // Anything else and we're using more than one mutex on this cvar,
273 // which is currently disallowed.
274 _ => panic!("attempted to use a condition variable with two \
284 use super::{StaticCondvar, CONDVAR_INIT};
285 use sync::mpsc::channel;
286 use sync::{StaticMutex, MUTEX_INIT, Condvar, Mutex, Arc};
292 let c = Condvar::new();
299 static C: StaticCondvar = CONDVAR_INIT;
302 unsafe { C.destroy(); }
307 static C: StaticCondvar = CONDVAR_INIT;
308 static M: StaticMutex = MUTEX_INIT;
310 let g = M.lock().unwrap();
311 let _t = Thread::spawn(move|| {
312 let _g = M.lock().unwrap();
315 let g = C.wait(g).unwrap();
317 unsafe { C.destroy(); M.destroy(); }
324 let data = Arc::new((Mutex::new(0), Condvar::new()));
325 let (tx, rx) = channel();
326 for _ in range(0, N) {
327 let data = data.clone();
329 Thread::spawn(move|| {
330 let &(ref lock, ref cond) = &*data;
331 let mut cnt = lock.lock().unwrap();
334 tx.send(()).unwrap();
337 cnt = cond.wait(cnt).unwrap();
339 tx.send(()).unwrap();
344 let &(ref lock, ref cond) = &*data;
346 let mut cnt = lock.lock().unwrap();
351 for _ in range(0, N) {
358 static C: StaticCondvar = CONDVAR_INIT;
359 static M: StaticMutex = MUTEX_INIT;
361 let g = M.lock().unwrap();
362 let (g, success) = C.wait_timeout(g, Duration::nanoseconds(1000)).unwrap();
364 let _t = Thread::spawn(move || {
365 let _g = M.lock().unwrap();
368 let (g, success) = C.wait_timeout(g, Duration::days(1)).unwrap();
371 unsafe { C.destroy(); M.destroy(); }
377 static M1: StaticMutex = MUTEX_INIT;
378 static M2: StaticMutex = MUTEX_INIT;
379 static C: StaticCondvar = CONDVAR_INIT;
381 let mut g = M1.lock().unwrap();
382 let _t = Thread::spawn(move|| {
383 let _g = M1.lock().unwrap();
386 g = C.wait(g).unwrap();
389 let _ = C.wait(M2.lock().unwrap()).unwrap();