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};
14 use sync::{mutex, MutexGuard, PoisonError};
15 use sys_common::condvar as sys;
16 use sys_common::mutex as sys_mutex;
17 use sys_common::poison::{self, LockResult};
18 use sys::time::SteadyTime;
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};
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();
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub struct Condvar { inner: Box<StaticCondvar> }
64 /// Statically allocated condition variables.
66 /// This structure is identical to `Condvar` except that it is suitable for use
67 /// in static initializers for other structures.
72 /// #![feature(static_condvar)]
74 /// use std::sync::{StaticCondvar, CONDVAR_INIT};
76 /// static CVAR: StaticCondvar = CONDVAR_INIT;
78 #[unstable(feature = "static_condvar",
79 reason = "may be merged with Condvar in the future",
81 pub struct StaticCondvar {
86 /// Constant initializer for a statically allocated condition variable.
87 #[unstable(feature = "static_condvar",
88 reason = "may be merged with Condvar in the future",
90 pub const CONDVAR_INIT: StaticCondvar = StaticCondvar::new();
93 /// Creates a new condition variable which is ready to be waited on and
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub fn new() -> Condvar {
98 inner: box StaticCondvar {
99 inner: sys::Condvar::new(),
100 mutex: AtomicUsize::new(0),
105 /// Blocks the current thread until this condition variable receives a
108 /// This function will atomically unlock the mutex specified (represented by
109 /// `mutex_guard`) and block the current thread. This means that any calls
110 /// to `notify_*()` which happen logically after the mutex is unlocked are
111 /// candidates to wake this thread up. When this function call returns, the
112 /// lock specified will have been re-acquired.
114 /// Note that this function is susceptible to spurious wakeups. Condition
115 /// variables normally have a boolean predicate associated with them, and
116 /// the predicate must always be checked each time this function returns to
117 /// protect against spurious wakeups.
121 /// This function will return an error if the mutex being waited on is
122 /// poisoned when this thread re-acquires the lock. For more information,
123 /// see information about poisoning on the Mutex type.
127 /// This function will `panic!()` if it is used with more than one mutex
128 /// over time. Each condition variable is dynamically bound to exactly one
129 /// mutex to ensure defined behavior across platforms. If this functionality
130 /// is not desired, then unsafe primitives in `sys` are provided.
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
133 -> LockResult<MutexGuard<'a, T>> {
135 let me: &'static Condvar = &*(self as *const _);
140 /// Waits on this condition variable for a notification, timing out after a
141 /// specified duration.
143 /// The semantics of this function are equivalent to `wait()`
144 /// except that the thread will be blocked for roughly no longer
145 /// than `ms` milliseconds. This method should not be used for
146 /// precise timing due to anomalies such as preemption or platform
147 /// differences that may not cause the maximum amount of time
148 /// waited to be precisely `ms`.
150 /// The returned boolean is `false` only if the timeout is known
153 /// Like `wait`, the lock specified will be re-acquired when this function
154 /// returns, regardless of whether the timeout elapsed or not.
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub fn wait_timeout_ms<'a, T>(&self, guard: MutexGuard<'a, T>, ms: u32)
157 -> LockResult<(MutexGuard<'a, T>, bool)> {
159 let me: &'static Condvar = &*(self as *const _);
160 me.inner.wait_timeout_ms(guard, ms)
164 /// Waits on this condition variable for a notification, timing out after a
165 /// specified duration.
167 /// The semantics of this function are equivalent to `wait()` except that
168 /// the thread will be blocked for roughly no longer than `dur`. This
169 /// method should not be used for precise timing due to anomalies such as
170 /// preemption or platform differences that may not cause the maximum
171 /// amount of time waited to be precisely `dur`.
173 /// The returned boolean is `false` only if the timeout is known
176 /// Like `wait`, the lock specified will be re-acquired when this function
177 /// returns, regardless of whether the timeout elapsed or not.
178 #[unstable(feature = "wait_timeout", reason = "waiting for Duration",
180 pub fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>,
182 -> LockResult<(MutexGuard<'a, T>, bool)> {
184 let me: &'static Condvar = &*(self as *const _);
185 me.inner.wait_timeout(guard, dur)
189 /// Waits on this condition variable for a notification, timing out after a
190 /// specified duration.
192 /// The semantics of this function are equivalent to `wait_timeout` except
193 /// that the implementation will repeatedly wait while the duration has not
194 /// passed and the provided function returns `false`.
195 #[unstable(feature = "wait_timeout_with",
196 reason = "unsure if this API is broadly needed or what form it should take",
198 pub fn wait_timeout_with<'a, T, F>(&self,
199 guard: MutexGuard<'a, T>,
202 -> LockResult<(MutexGuard<'a, T>, bool)>
203 where F: FnMut(LockResult<&mut T>) -> bool {
205 let me: &'static Condvar = &*(self as *const _);
206 me.inner.wait_timeout_with(guard, dur, f)
210 /// Wakes up one blocked thread on this condvar.
212 /// If there is a blocked thread on this condition variable, then it will
213 /// be woken up from its call to `wait` or `wait_timeout`. Calls to
214 /// `notify_one` are not buffered in any way.
216 /// To wake up all threads, see `notify_all()`.
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } }
220 /// Wakes up all blocked threads on this condvar.
222 /// This method will ensure that any current waiters on the condition
223 /// variable are awoken. Calls to `notify_all()` are not buffered in any
226 /// To wake up only one thread, see `notify_one()`.
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } }
231 #[stable(feature = "rust1", since = "1.0.0")]
232 impl Drop for Condvar {
234 unsafe { self.inner.inner.destroy() }
239 /// Creates a new condition variable
240 #[unstable(feature = "static_condvar",
241 reason = "may be merged with Condvar in the future",
243 pub const fn new() -> StaticCondvar {
245 inner: sys::Condvar::new(),
246 mutex: AtomicUsize::new(0),
250 /// Blocks the current thread until this condition variable receives a
253 /// See `Condvar::wait`.
254 #[unstable(feature = "static_condvar",
255 reason = "may be merged with Condvar in the future",
257 pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
258 -> LockResult<MutexGuard<'a, T>> {
259 let poisoned = unsafe {
260 let lock = mutex::guard_lock(&guard);
262 self.inner.wait(lock);
263 mutex::guard_poison(&guard).get()
266 Err(PoisonError::new(guard))
272 /// Waits on this condition variable for a notification, timing out after a
273 /// specified duration.
275 /// See `Condvar::wait_timeout`.
276 #[unstable(feature = "static_condvar",
277 reason = "may be merged with Condvar in the future",
279 pub fn wait_timeout_ms<'a, T>(&'static self, guard: MutexGuard<'a, T>, ms: u32)
280 -> LockResult<(MutexGuard<'a, T>, bool)> {
281 self.wait_timeout(guard, Duration::from_millis(ms as u64))
284 /// Waits on this condition variable for a notification, timing out after a
285 /// specified duration.
287 /// See `Condvar::wait_timeout`.
288 #[unstable(feature = "static_condvar",
289 reason = "may be merged with Condvar in the future",
291 pub fn wait_timeout<'a, T>(&'static self,
292 guard: MutexGuard<'a, T>,
294 -> LockResult<(MutexGuard<'a, T>, bool)> {
295 let (poisoned, success) = unsafe {
296 let lock = mutex::guard_lock(&guard);
298 let success = self.inner.wait_timeout(lock, timeout);
299 (mutex::guard_poison(&guard).get(), success)
302 Err(PoisonError::new((guard, success)))
308 /// Waits on this condition variable for a notification, timing out after a
309 /// specified duration.
311 /// The implementation will repeatedly wait while the duration has not
312 /// passed and the function returns `false`.
314 /// See `Condvar::wait_timeout_with`.
315 #[unstable(feature = "static_condvar",
316 reason = "may be merged with Condvar in the future",
318 pub fn wait_timeout_with<'a, T, F>(&'static self,
319 guard: MutexGuard<'a, T>,
322 -> LockResult<(MutexGuard<'a, T>, bool)>
323 where F: FnMut(LockResult<&mut T>) -> bool {
324 // This could be made more efficient by pushing the implementation into
326 let start = SteadyTime::now();
327 let mut guard_result: LockResult<MutexGuard<'a, T>> = Ok(guard);
328 while !f(guard_result
331 .map_err(|e| PoisonError::new(&mut **e.get_mut()))) {
332 let now = SteadyTime::now();
333 let consumed = &now - &start;
334 let guard = guard_result.unwrap_or_else(|e| e.into_inner());
335 let (new_guard_result, no_timeout) = if consumed > dur {
338 match self.wait_timeout(guard, dur - consumed) {
339 Ok((new_guard, no_timeout)) => (Ok(new_guard), no_timeout),
341 let (new_guard, no_timeout) = err.into_inner();
342 (Err(PoisonError::new(new_guard)), no_timeout)
346 guard_result = new_guard_result;
348 let result = f(guard_result
351 .map_err(|e| PoisonError::new(&mut **e.get_mut())));
352 return poison::map_result(guard_result, |g| (g, result));
356 poison::map_result(guard_result, |g| (g, true))
359 /// Wakes up one blocked thread on this condvar.
361 /// See `Condvar::notify_one`.
362 #[unstable(feature = "static_condvar",
363 reason = "may be merged with Condvar in the future",
365 pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
367 /// Wakes up all blocked threads on this condvar.
369 /// See `Condvar::notify_all`.
370 #[unstable(feature = "static_condvar",
371 reason = "may be merged with Condvar in the future",
373 pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
375 /// Deallocates all resources associated with this static condvar.
377 /// This method is unsafe to call as there is no guarantee that there are no
378 /// active users of the condvar, and this also doesn't prevent any future
379 /// users of the condvar. This method is required to be called to not leak
380 /// memory on all platforms.
381 #[unstable(feature = "static_condvar",
382 reason = "may be merged with Condvar in the future",
384 pub unsafe fn destroy(&'static self) {
388 fn verify(&self, mutex: &sys_mutex::Mutex) {
389 let addr = mutex as *const _ as usize;
390 match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
391 // If we got out 0, then we have successfully bound the mutex to
395 // If we get out a value that's the same as `addr`, then someone
396 // already beat us to the punch.
399 // Anything else and we're using more than one mutex on this cvar,
400 // which is currently disallowed.
401 _ => panic!("attempted to use a condition variable with two \
411 use super::StaticCondvar;
412 use sync::mpsc::channel;
413 use sync::{StaticMutex, Condvar, Mutex, Arc};
414 use sync::atomic::{AtomicUsize, Ordering};
421 let c = Condvar::new();
428 static C: StaticCondvar = StaticCondvar::new();
431 unsafe { C.destroy(); }
436 static C: StaticCondvar = StaticCondvar::new();
437 static M: StaticMutex = StaticMutex::new();
439 let g = M.lock().unwrap();
440 let _t = thread::spawn(move|| {
441 let _g = M.lock().unwrap();
444 let g = C.wait(g).unwrap();
446 unsafe { C.destroy(); M.destroy(); }
453 let data = Arc::new((Mutex::new(0), Condvar::new()));
454 let (tx, rx) = channel();
456 let data = data.clone();
458 thread::spawn(move|| {
459 let &(ref lock, ref cond) = &*data;
460 let mut cnt = lock.lock().unwrap();
463 tx.send(()).unwrap();
466 cnt = cond.wait(cnt).unwrap();
468 tx.send(()).unwrap();
473 let &(ref lock, ref cond) = &*data;
475 let mut cnt = lock.lock().unwrap();
486 fn wait_timeout_ms() {
487 static C: StaticCondvar = StaticCondvar::new();
488 static M: StaticMutex = StaticMutex::new();
490 let g = M.lock().unwrap();
491 let (g, _no_timeout) = C.wait_timeout_ms(g, 1).unwrap();
492 // spurious wakeups mean this isn't necessarily true
493 // assert!(!no_timeout);
494 let _t = thread::spawn(move || {
495 let _g = M.lock().unwrap();
498 let (g, no_timeout) = C.wait_timeout_ms(g, u32::MAX).unwrap();
501 unsafe { C.destroy(); M.destroy(); }
505 fn wait_timeout_with() {
506 static C: StaticCondvar = StaticCondvar::new();
507 static M: StaticMutex = StaticMutex::new();
508 static S: AtomicUsize = AtomicUsize::new(0);
510 let g = M.lock().unwrap();
511 let (g, success) = C.wait_timeout_with(g, Duration::new(0, 1000), |_| {
516 let (tx, rx) = channel();
517 let _t = thread::spawn(move || {
519 let g = M.lock().unwrap();
520 S.store(1, Ordering::SeqCst);
525 let g = M.lock().unwrap();
526 S.store(2, Ordering::SeqCst);
531 let _g = M.lock().unwrap();
532 S.store(3, Ordering::SeqCst);
537 let day = 24 * 60 * 60;
538 let (_g, success) = C.wait_timeout_with(g, Duration::new(day, 0), |_| {
539 assert_eq!(state, S.load(Ordering::SeqCst));
540 tx.send(()).unwrap();
553 static M1: StaticMutex = StaticMutex::new();
554 static M2: StaticMutex = StaticMutex::new();
555 static C: StaticCondvar = StaticCondvar::new();
557 let mut g = M1.lock().unwrap();
558 let _t = thread::spawn(move|| {
559 let _g = M1.lock().unwrap();
562 g = C.wait(g).unwrap();
565 let _ = C.wait(M2.lock().unwrap()).unwrap();