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::time::SteadyTime;
16 use sys_common::condvar as sys;
17 use sys_common::mutex as sys_mutex;
19 use sync::{mutex, MutexGuard};
21 /// A Condition Variable
23 /// Condition variables represent the ability to block a thread such that it
24 /// consumes no CPU time while waiting for an event to occur. Condition
25 /// variables are typically associated with a boolean predicate (a condition)
26 /// and a mutex. The predicate is always verified inside of the mutex before
27 /// determining that thread must block.
29 /// Functions in this module will block the current **thread** of execution and
30 /// are bindings to system-provided condition variables where possible. Note
31 /// that this module places one additional restriction over the system condition
32 /// variables: each condvar can be used with precisely one mutex at runtime. Any
33 /// attempt to use multiple mutexes on the same condition variable will result
34 /// in a runtime panic. If this is not desired, then the unsafe primitives in
35 /// `sys` do not have this restriction but may result in undefined behavior.
40 /// use std::sync::{Arc, Mutex, Condvar};
41 /// use std::thread::Thread;
43 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
44 /// let pair2 = pair.clone();
46 /// // Inside of our lock, spawn a new thread, and then wait for it to start
47 /// Thread::spawn(move|| {
48 /// let &(ref lock, ref cvar) = &*pair2;
49 /// let mut started = lock.lock().unwrap();
51 /// cvar.notify_one();
54 /// // wait for the thread to start up
55 /// let &(ref lock, ref cvar) = &*pair;
56 /// let mut started = lock.lock().unwrap();
58 /// started = cvar.wait(started).unwrap();
62 pub struct Condvar { inner: Box<StaticCondvar> }
64 unsafe impl Send for Condvar {}
65 unsafe impl Sync for Condvar {}
67 /// Statically allocated condition variables.
69 /// This structure is identical to `Condvar` except that it is suitable for use
70 /// in static initializers for other structures.
75 /// use std::sync::{StaticCondvar, CONDVAR_INIT};
77 /// static CVAR: StaticCondvar = CONDVAR_INIT;
79 #[unstable = "may be merged with Condvar in the future"]
80 pub struct StaticCondvar {
85 unsafe impl Send for StaticCondvar {}
86 unsafe impl Sync for StaticCondvar {}
88 /// Constant initializer for a statically allocated condition variable.
89 #[unstable = "may be merged with Condvar in the future"]
90 pub const CONDVAR_INIT: StaticCondvar = StaticCondvar {
91 inner: sys::CONDVAR_INIT,
92 mutex: ATOMIC_USIZE_INIT,
96 /// Creates a new condition variable which is ready to be waited on and
99 pub fn new() -> Condvar {
101 inner: box StaticCondvar {
102 inner: unsafe { sys::Condvar::new() },
103 mutex: AtomicUsize::new(0),
108 /// Block the current thread until this condition variable receives a
111 /// This function will atomically unlock the mutex specified (represented by
112 /// `mutex_guard`) and block the current thread. This means that any calls
113 /// to `notify_*()` which happen logically after the mutex is unlocked are
114 /// candidates to wake this thread up. When this function call returns, the
115 /// lock specified will have been re-acquired.
117 /// Note that this function is susceptible to spurious wakeups. Condition
118 /// variables normally have a boolean predicate associated with them, and
119 /// the predicate must always be checked each time this function returns to
120 /// protect against spurious wakeups.
124 /// This function will return an error if the mutex being waited on is
125 /// poisoned when this thread re-acquires the lock. For more information,
126 /// see information about poisoning on the Mutex type.
130 /// This function will `panic!()` if it is used with more than one mutex
131 /// over time. Each condition variable is dynamically bound to exactly one
132 /// mutex to ensure defined behavior across platforms. If this functionality
133 /// is not desired, then unsafe primitives in `sys` are provided.
135 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
136 -> LockResult<MutexGuard<'a, T>> {
138 let me: &'static Condvar = &*(self as *const _);
143 /// Wait on this condition variable for a notification, timing out after a
144 /// specified duration.
146 /// The semantics of this function are equivalent to `wait()` except that
147 /// the thread will be blocked for roughly no longer than `dur`. This method
148 /// should not be used for precise timing due to anomalies such as
149 /// preemption or platform differences that may not cause the maximum amount
150 /// of time waited to be precisely `dur`.
152 /// If the wait timed out, then `false` will be returned. Otherwise if a
153 /// notification was received then `true` will be returned.
155 /// Like `wait`, the lock specified will be re-acquired when this function
156 /// returns, regardless of whether the timeout elapsed or not.
158 pub fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>, dur: Duration)
159 -> LockResult<(MutexGuard<'a, T>, bool)> {
161 let me: &'static Condvar = &*(self as *const _);
162 me.inner.wait_timeout(guard, dur)
166 /// Wait on this condition variable for a notification, timing out after a
167 /// specified duration.
169 /// The semantics of this function are equivalent to `wait_timeout` except
170 /// that the implementation will repeatedly wait while the duration has not
171 /// passed and the provided function returns `false`.
173 pub fn wait_timeout_with<'a, T, F>(&self,
174 guard: MutexGuard<'a, T>,
177 -> LockResult<(MutexGuard<'a, T>, bool)>
178 where F: FnMut(LockResult<&mut T>) -> bool {
180 let me: &'static Condvar = &*(self as *const _);
181 me.inner.wait_timeout_with(guard, dur, f)
185 /// Wake up one blocked thread on this condvar.
187 /// If there is a blocked thread on this condition variable, then it will
188 /// be woken up from its call to `wait` or `wait_timeout`. Calls to
189 /// `notify_one` are not buffered in any way.
191 /// To wake up all threads, see `notify_all()`.
193 pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } }
195 /// Wake up all blocked threads on this condvar.
197 /// This method will ensure that any current waiters on the condition
198 /// variable are awoken. Calls to `notify_all()` are not buffered in any
201 /// To wake up only one thread, see `notify_one()`.
203 pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } }
207 impl Drop for Condvar {
209 unsafe { self.inner.inner.destroy() }
214 /// Block the current thread until this condition variable receives a
217 /// See `Condvar::wait`.
218 #[unstable = "may be merged with Condvar in the future"]
219 pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
220 -> LockResult<MutexGuard<'a, T>> {
221 let poisoned = unsafe {
222 let lock = mutex::guard_lock(&guard);
224 self.inner.wait(lock);
225 mutex::guard_poison(&guard).get()
228 Err(poison::new_poison_error(guard))
234 /// Wait on this condition variable for a notification, timing out after a
235 /// specified duration.
237 /// See `Condvar::wait_timeout`.
238 #[unstable = "may be merged with Condvar in the future"]
239 pub fn wait_timeout<'a, T>(&'static self, guard: MutexGuard<'a, T>, dur: Duration)
240 -> LockResult<(MutexGuard<'a, T>, bool)> {
241 let (poisoned, success) = unsafe {
242 let lock = mutex::guard_lock(&guard);
244 let success = self.inner.wait_timeout(lock, dur);
245 (mutex::guard_poison(&guard).get(), success)
248 Err(poison::new_poison_error((guard, success)))
254 /// Wait on this condition variable for a notification, timing out after a
255 /// specified duration.
257 /// The implementation will repeatedly wait while the duration has not
258 /// passed and the function returns `false`.
260 /// See `Condvar::wait_timeout_with`.
261 #[unstable = "may be merged with Condvar in the future"]
262 pub fn wait_timeout_with<'a, T, F>(&'static self,
263 guard: MutexGuard<'a, T>,
266 -> LockResult<(MutexGuard<'a, T>, bool)>
267 where F: FnMut(LockResult<&mut T>) -> bool {
268 // This could be made more efficient by pushing the implementation into sys::condvar
269 let start = SteadyTime::now();
270 let mut guard_result: LockResult<MutexGuard<'a, T>> = Ok(guard);
271 while !f(guard_result
274 .map_err(|e| poison::new_poison_error(&mut **e.get_mut()))) {
275 let now = SteadyTime::now();
276 let consumed = &now - &start;
277 let guard = guard_result.unwrap_or_else(|e| e.into_inner());
278 let (new_guard_result, no_timeout) = match self.wait_timeout(guard, dur - consumed) {
279 Ok((new_guard, no_timeout)) => (Ok(new_guard), no_timeout),
281 let (new_guard, no_timeout) = err.into_inner();
282 (Err(poison::new_poison_error(new_guard)), no_timeout)
285 guard_result = new_guard_result;
287 let result = f(guard_result
290 .map_err(|e| poison::new_poison_error(&mut **e.get_mut())));
291 return poison::map_result(guard_result, |g| (g, result));
295 poison::map_result(guard_result, |g| (g, true))
298 /// Wake up one blocked thread on this condvar.
300 /// See `Condvar::notify_one`.
301 #[unstable = "may be merged with Condvar in the future"]
302 pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
304 /// Wake up all blocked threads on this condvar.
306 /// See `Condvar::notify_all`.
307 #[unstable = "may be merged with Condvar in the future"]
308 pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
310 /// Deallocate all resources associated with this static condvar.
312 /// This method is unsafe to call as there is no guarantee that there are no
313 /// active users of the condvar, and this also doesn't prevent any future
314 /// users of the condvar. This method is required to be called to not leak
315 /// memory on all platforms.
316 #[unstable = "may be merged with Condvar in the future"]
317 pub unsafe fn destroy(&'static self) {
321 fn verify(&self, mutex: &sys_mutex::Mutex) {
322 let addr = mutex as *const _ as uint;
323 match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
324 // If we got out 0, then we have successfully bound the mutex to
328 // If we get out a value that's the same as `addr`, then someone
329 // already beat us to the punch.
332 // Anything else and we're using more than one mutex on this cvar,
333 // which is currently disallowed.
334 _ => panic!("attempted to use a condition variable with two \
344 use super::{StaticCondvar, CONDVAR_INIT};
345 use sync::mpsc::channel;
346 use sync::{StaticMutex, MUTEX_INIT, Condvar, Mutex, Arc};
347 use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
353 let c = Condvar::new();
360 static C: StaticCondvar = CONDVAR_INIT;
363 unsafe { C.destroy(); }
368 static C: StaticCondvar = CONDVAR_INIT;
369 static M: StaticMutex = MUTEX_INIT;
371 let g = M.lock().unwrap();
372 let _t = Thread::spawn(move|| {
373 let _g = M.lock().unwrap();
376 let g = C.wait(g).unwrap();
378 unsafe { C.destroy(); M.destroy(); }
385 let data = Arc::new((Mutex::new(0), Condvar::new()));
386 let (tx, rx) = channel();
387 for _ in range(0, N) {
388 let data = data.clone();
390 Thread::spawn(move|| {
391 let &(ref lock, ref cond) = &*data;
392 let mut cnt = lock.lock().unwrap();
395 tx.send(()).unwrap();
398 cnt = cond.wait(cnt).unwrap();
400 tx.send(()).unwrap();
405 let &(ref lock, ref cond) = &*data;
407 let mut cnt = lock.lock().unwrap();
412 for _ in range(0, N) {
419 static C: StaticCondvar = CONDVAR_INIT;
420 static M: StaticMutex = MUTEX_INIT;
422 let g = M.lock().unwrap();
423 let (g, success) = C.wait_timeout(g, Duration::nanoseconds(1000)).unwrap();
425 let _t = Thread::spawn(move || {
426 let _g = M.lock().unwrap();
429 let (g, success) = C.wait_timeout(g, Duration::days(1)).unwrap();
432 unsafe { C.destroy(); M.destroy(); }
436 fn wait_timeout_with() {
437 static C: StaticCondvar = CONDVAR_INIT;
438 static M: StaticMutex = MUTEX_INIT;
439 static S: AtomicUsize = ATOMIC_USIZE_INIT;
441 let g = M.lock().unwrap();
442 let (g, success) = C.wait_timeout_with(g, Duration::nanoseconds(1000), |_| false).unwrap();
445 let (tx, rx) = channel();
446 let _t = Thread::scoped(move || {
448 let g = M.lock().unwrap();
449 S.store(1, Ordering::SeqCst);
454 let g = M.lock().unwrap();
455 S.store(2, Ordering::SeqCst);
460 let _g = M.lock().unwrap();
461 S.store(3, Ordering::SeqCst);
466 let (_g, success) = C.wait_timeout_with(g, Duration::days(1), |_| {
467 assert_eq!(state, S.load(Ordering::SeqCst));
468 tx.send(()).unwrap();
481 static M1: StaticMutex = MUTEX_INIT;
482 static M2: StaticMutex = MUTEX_INIT;
483 static C: StaticCondvar = CONDVAR_INIT;
485 let mut g = M1.lock().unwrap();
486 let _t = Thread::spawn(move|| {
487 let _g = M1.lock().unwrap();
490 g = C.wait(g).unwrap();
493 let _ = C.wait(M2.lock().unwrap()).unwrap();