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::{AtomicUsize, Ordering, ATOMIC_USIZE_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_USIZE_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: AtomicUsize::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_all()`.
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() } }
192 impl Drop for Condvar {
194 unsafe { self.inner.inner.destroy() }
199 /// Block the current thread until this condition variable receives a
202 /// See `Condvar::wait`.
203 #[unstable = "may be merged with Condvar in the future"]
204 pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
205 -> LockResult<MutexGuard<'a, T>> {
206 let poisoned = unsafe {
207 let lock = mutex::guard_lock(&guard);
209 self.inner.wait(lock);
210 mutex::guard_poison(&guard).get()
213 Err(poison::new_poison_error(guard))
219 /// Wait on this condition variable for a notification, timing out after a
220 /// specified duration.
222 /// See `Condvar::wait_timeout`.
223 #[allow(dead_code)] // may want to stabilize this later, see wait_timeout above
224 fn wait_timeout<'a, T>(&'static self, guard: MutexGuard<'a, T>, dur: Duration)
225 -> LockResult<(MutexGuard<'a, T>, bool)> {
226 let (poisoned, success) = unsafe {
227 let lock = mutex::guard_lock(&guard);
229 let success = self.inner.wait_timeout(lock, dur);
230 (mutex::guard_poison(&guard).get(), success)
233 Err(poison::new_poison_error((guard, success)))
239 /// Wake up one blocked thread on this condvar.
241 /// See `Condvar::notify_one`.
242 #[unstable = "may be merged with Condvar in the future"]
243 pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
245 /// Wake up all blocked threads on this condvar.
247 /// See `Condvar::notify_all`.
248 #[unstable = "may be merged with Condvar in the future"]
249 pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
251 /// Deallocate all resources associated with this static condvar.
253 /// This method is unsafe to call as there is no guarantee that there are no
254 /// active users of the condvar, and this also doesn't prevent any future
255 /// users of the condvar. This method is required to be called to not leak
256 /// memory on all platforms.
257 #[unstable = "may be merged with Condvar in the future"]
258 pub unsafe fn destroy(&'static self) {
262 fn verify(&self, mutex: &sys_mutex::Mutex) {
263 let addr = mutex as *const _ as uint;
264 match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
265 // If we got out 0, then we have successfully bound the mutex to
269 // If we get out a value that's the same as `addr`, then someone
270 // already beat us to the punch.
273 // Anything else and we're using more than one mutex on this cvar,
274 // which is currently disallowed.
275 _ => panic!("attempted to use a condition variable with two \
285 use super::{StaticCondvar, CONDVAR_INIT};
286 use sync::mpsc::channel;
287 use sync::{StaticMutex, MUTEX_INIT, Condvar, Mutex, Arc};
293 let c = Condvar::new();
300 static C: StaticCondvar = CONDVAR_INIT;
303 unsafe { C.destroy(); }
308 static C: StaticCondvar = CONDVAR_INIT;
309 static M: StaticMutex = MUTEX_INIT;
311 let g = M.lock().unwrap();
312 let _t = Thread::spawn(move|| {
313 let _g = M.lock().unwrap();
316 let g = C.wait(g).unwrap();
318 unsafe { C.destroy(); M.destroy(); }
325 let data = Arc::new((Mutex::new(0), Condvar::new()));
326 let (tx, rx) = channel();
327 for _ in range(0, N) {
328 let data = data.clone();
330 Thread::spawn(move|| {
331 let &(ref lock, ref cond) = &*data;
332 let mut cnt = lock.lock().unwrap();
335 tx.send(()).unwrap();
338 cnt = cond.wait(cnt).unwrap();
340 tx.send(()).unwrap();
345 let &(ref lock, ref cond) = &*data;
347 let mut cnt = lock.lock().unwrap();
352 for _ in range(0, N) {
359 static C: StaticCondvar = CONDVAR_INIT;
360 static M: StaticMutex = MUTEX_INIT;
362 let g = M.lock().unwrap();
363 let (g, success) = C.wait_timeout(g, Duration::nanoseconds(1000)).unwrap();
365 let _t = Thread::spawn(move || {
366 let _g = M.lock().unwrap();
369 let (g, success) = C.wait_timeout(g, Duration::days(1)).unwrap();
372 unsafe { C.destroy(); M.destroy(); }
378 static M1: StaticMutex = MUTEX_INIT;
379 static M2: StaticMutex = MUTEX_INIT;
380 static C: StaticCondvar = CONDVAR_INIT;
382 let mut g = M1.lock().unwrap();
383 let _t = Thread::spawn(move|| {
384 let _g = M1.lock().unwrap();
387 g = C.wait(g).unwrap();
390 let _ = C.wait(M2.lock().unwrap()).unwrap();