5 use crate::sync::{mutex, poison, LockResult, MutexGuard, PoisonError};
6 use crate::sys_common::condvar as sys;
7 use crate::time::{Duration, Instant};
9 /// A type indicating whether a timed wait on a condition variable returned
10 /// due to a time out or not.
12 /// It is returned by the [`wait_timeout`] method.
14 /// [`wait_timeout`]: Condvar::wait_timeout
15 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
16 #[stable(feature = "wait_timeout", since = "1.5.0")]
17 pub struct WaitTimeoutResult(bool);
19 impl WaitTimeoutResult {
20 /// Returns `true` if the wait was known to have timed out.
24 /// This example spawns a thread which will update the boolean value and
25 /// then wait 100 milliseconds before notifying the condvar.
27 /// The main thread will wait with a timeout on the condvar and then leave
28 /// once the boolean has been updated and notified.
31 /// use std::sync::{Arc, Condvar, Mutex};
33 /// use std::time::Duration;
35 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
36 /// let pair2 = Arc::clone(&pair);
38 /// thread::spawn(move || {
39 /// let (lock, cvar) = &*pair2;
41 /// // Let's wait 20 milliseconds before notifying the condvar.
42 /// thread::sleep(Duration::from_millis(20));
44 /// let mut started = lock.lock().unwrap();
45 /// // We update the boolean value.
47 /// cvar.notify_one();
50 /// // Wait for the thread to start up.
51 /// let (lock, cvar) = &*pair;
52 /// let mut started = lock.lock().unwrap();
54 /// // Let's put a timeout on the condvar's wait.
55 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
56 /// // 10 milliseconds have passed, or maybe the value changed!
57 /// started = result.0;
58 /// if *started == true {
59 /// // We received the notification and the value has been updated, we can leave.
64 #[stable(feature = "wait_timeout", since = "1.5.0")]
65 pub fn timed_out(&self) -> bool {
70 /// A Condition Variable
72 /// Condition variables represent the ability to block a thread such that it
73 /// consumes no CPU time while waiting for an event to occur. Condition
74 /// variables are typically associated with a boolean predicate (a condition)
75 /// and a mutex. The predicate is always verified inside of the mutex before
76 /// determining that a thread must block.
78 /// Functions in this module will block the current **thread** of execution.
79 /// Note that any attempt to use multiple mutexes on the same condition
80 /// variable may result in a runtime panic.
85 /// use std::sync::{Arc, Mutex, Condvar};
88 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
89 /// let pair2 = Arc::clone(&pair);
91 /// // Inside of our lock, spawn a new thread, and then wait for it to start.
92 /// thread::spawn(move|| {
93 /// let (lock, cvar) = &*pair2;
94 /// let mut started = lock.lock().unwrap();
96 /// // We notify the condvar that the value has changed.
97 /// cvar.notify_one();
100 /// // Wait for the thread to start up.
101 /// let (lock, cvar) = &*pair;
102 /// let mut started = lock.lock().unwrap();
103 /// while !*started {
104 /// started = cvar.wait(started).unwrap();
107 #[stable(feature = "rust1", since = "1.0.0")]
113 /// Creates a new condition variable which is ready to be waited on and
119 /// use std::sync::Condvar;
121 /// let condvar = Condvar::new();
123 #[stable(feature = "rust1", since = "1.0.0")]
124 pub fn new() -> Condvar {
125 Condvar { inner: sys::Condvar::new() }
128 /// Blocks the current thread until this condition variable receives a
131 /// This function will atomically unlock the mutex specified (represented by
132 /// `guard`) and block the current thread. This means that any calls
133 /// to [`notify_one`] or [`notify_all`] which happen logically after the
134 /// mutex is unlocked are candidates to wake this thread up. When this
135 /// function call returns, the lock specified will have been re-acquired.
137 /// Note that this function is susceptible to spurious wakeups. Condition
138 /// variables normally have a boolean predicate associated with them, and
139 /// the predicate must always be checked each time this function returns to
140 /// protect against spurious wakeups.
144 /// This function will return an error if the mutex being waited on is
145 /// poisoned when this thread re-acquires the lock. For more information,
146 /// see information about [poisoning] on the [`Mutex`] type.
150 /// This function may [`panic!`] if it is used with more than one mutex
153 /// [`notify_one`]: Self::notify_one
154 /// [`notify_all`]: Self::notify_all
155 /// [poisoning]: super::Mutex#poisoning
156 /// [`Mutex`]: super::Mutex
161 /// use std::sync::{Arc, Mutex, Condvar};
164 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
165 /// let pair2 = Arc::clone(&pair);
167 /// thread::spawn(move|| {
168 /// let (lock, cvar) = &*pair2;
169 /// let mut started = lock.lock().unwrap();
171 /// // We notify the condvar that the value has changed.
172 /// cvar.notify_one();
175 /// // Wait for the thread to start up.
176 /// let (lock, cvar) = &*pair;
177 /// let mut started = lock.lock().unwrap();
178 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
179 /// while !*started {
180 /// started = cvar.wait(started).unwrap();
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
185 let poisoned = unsafe {
186 let lock = mutex::guard_lock(&guard);
187 self.inner.wait(lock);
188 mutex::guard_poison(&guard).get()
190 if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
193 /// Blocks the current thread until this condition variable receives a
194 /// notification and the provided condition is false.
196 /// This function will atomically unlock the mutex specified (represented by
197 /// `guard`) and block the current thread. This means that any calls
198 /// to [`notify_one`] or [`notify_all`] which happen logically after the
199 /// mutex is unlocked are candidates to wake this thread up. When this
200 /// function call returns, the lock specified will have been re-acquired.
204 /// This function will return an error if the mutex being waited on is
205 /// poisoned when this thread re-acquires the lock. For more information,
206 /// see information about [poisoning] on the [`Mutex`] type.
208 /// [`notify_one`]: Self::notify_one
209 /// [`notify_all`]: Self::notify_all
210 /// [poisoning]: super::Mutex#poisoning
211 /// [`Mutex`]: super::Mutex
216 /// use std::sync::{Arc, Mutex, Condvar};
219 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
220 /// let pair2 = Arc::clone(&pair);
222 /// thread::spawn(move|| {
223 /// let (lock, cvar) = &*pair2;
224 /// let mut pending = lock.lock().unwrap();
225 /// *pending = false;
226 /// // We notify the condvar that the value has changed.
227 /// cvar.notify_one();
230 /// // Wait for the thread to start up.
231 /// let (lock, cvar) = &*pair;
232 /// // As long as the value inside the `Mutex<bool>` is `true`, we wait.
233 /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
235 #[stable(feature = "wait_until", since = "1.42.0")]
236 pub fn wait_while<'a, T, F>(
238 mut guard: MutexGuard<'a, T>,
240 ) -> LockResult<MutexGuard<'a, T>>
242 F: FnMut(&mut T) -> bool,
244 while condition(&mut *guard) {
245 guard = self.wait(guard)?;
250 /// Waits on this condition variable for a notification, timing out after a
251 /// specified duration.
253 /// The semantics of this function are equivalent to [`wait`]
254 /// except that the thread will be blocked for roughly no longer
255 /// than `ms` milliseconds. This method should not be used for
256 /// precise timing due to anomalies such as preemption or platform
257 /// differences that might not cause the maximum amount of time
258 /// waited to be precisely `ms`.
260 /// Note that the best effort is made to ensure that the time waited is
261 /// measured with a monotonic clock, and not affected by the changes made to
264 /// The returned boolean is `false` only if the timeout is known
267 /// Like [`wait`], the lock specified will be re-acquired when this function
268 /// returns, regardless of whether the timeout elapsed or not.
270 /// [`wait`]: Self::wait
275 /// use std::sync::{Arc, Mutex, Condvar};
278 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
279 /// let pair2 = Arc::clone(&pair);
281 /// thread::spawn(move|| {
282 /// let (lock, cvar) = &*pair2;
283 /// let mut started = lock.lock().unwrap();
285 /// // We notify the condvar that the value has changed.
286 /// cvar.notify_one();
289 /// // Wait for the thread to start up.
290 /// let (lock, cvar) = &*pair;
291 /// let mut started = lock.lock().unwrap();
292 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
294 /// let result = cvar.wait_timeout_ms(started, 10).unwrap();
295 /// // 10 milliseconds have passed, or maybe the value changed!
296 /// started = result.0;
297 /// if *started == true {
298 /// // We received the notification and the value has been updated, we can leave.
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::sync::Condvar::wait_timeout`")]
305 pub fn wait_timeout_ms<'a, T>(
307 guard: MutexGuard<'a, T>,
309 ) -> LockResult<(MutexGuard<'a, T>, bool)> {
310 let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
311 poison::map_result(res, |(a, b)| (a, !b.timed_out()))
314 /// Waits on this condition variable for a notification, timing out after a
315 /// specified duration.
317 /// The semantics of this function are equivalent to [`wait`] except that
318 /// the thread will be blocked for roughly no longer than `dur`. This
319 /// method should not be used for precise timing due to anomalies such as
320 /// preemption or platform differences that might not cause the maximum
321 /// amount of time waited to be precisely `dur`.
323 /// Note that the best effort is made to ensure that the time waited is
324 /// measured with a monotonic clock, and not affected by the changes made to
325 /// the system time. This function is susceptible to spurious wakeups.
326 /// Condition variables normally have a boolean predicate associated with
327 /// them, and the predicate must always be checked each time this function
328 /// returns to protect against spurious wakeups. Additionally, it is
329 /// typically desirable for the timeout to not exceed some duration in
330 /// spite of spurious wakes, thus the sleep-duration is decremented by the
331 /// amount slept. Alternatively, use the `wait_timeout_while` method
332 /// to wait with a timeout while a predicate is true.
334 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
335 /// known to have elapsed.
337 /// Like [`wait`], the lock specified will be re-acquired when this function
338 /// returns, regardless of whether the timeout elapsed or not.
340 /// [`wait`]: Self::wait
341 /// [`wait_timeout_while`]: Self::wait_timeout_while
346 /// use std::sync::{Arc, Mutex, Condvar};
348 /// use std::time::Duration;
350 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
351 /// let pair2 = Arc::clone(&pair);
353 /// thread::spawn(move|| {
354 /// let (lock, cvar) = &*pair2;
355 /// let mut started = lock.lock().unwrap();
357 /// // We notify the condvar that the value has changed.
358 /// cvar.notify_one();
361 /// // wait for the thread to start up
362 /// let (lock, cvar) = &*pair;
363 /// let mut started = lock.lock().unwrap();
364 /// // as long as the value inside the `Mutex<bool>` is `false`, we wait
366 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
367 /// // 10 milliseconds have passed, or maybe the value changed!
368 /// started = result.0;
369 /// if *started == true {
370 /// // We received the notification and the value has been updated, we can leave.
375 #[stable(feature = "wait_timeout", since = "1.5.0")]
376 pub fn wait_timeout<'a, T>(
378 guard: MutexGuard<'a, T>,
380 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
381 let (poisoned, result) = unsafe {
382 let lock = mutex::guard_lock(&guard);
383 let success = self.inner.wait_timeout(lock, dur);
384 (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
386 if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
389 /// Waits on this condition variable for a notification, timing out after a
390 /// specified duration.
392 /// The semantics of this function are equivalent to [`wait_while`] except
393 /// that the thread will be blocked for roughly no longer than `dur`. This
394 /// method should not be used for precise timing due to anomalies such as
395 /// preemption or platform differences that might not cause the maximum
396 /// amount of time waited to be precisely `dur`.
398 /// Note that the best effort is made to ensure that the time waited is
399 /// measured with a monotonic clock, and not affected by the changes made to
402 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
403 /// known to have elapsed without the condition being met.
405 /// Like [`wait_while`], the lock specified will be re-acquired when this
406 /// function returns, regardless of whether the timeout elapsed or not.
408 /// [`wait_while`]: Self::wait_while
409 /// [`wait_timeout`]: Self::wait_timeout
414 /// use std::sync::{Arc, Mutex, Condvar};
416 /// use std::time::Duration;
418 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
419 /// let pair2 = Arc::clone(&pair);
421 /// thread::spawn(move|| {
422 /// let (lock, cvar) = &*pair2;
423 /// let mut pending = lock.lock().unwrap();
424 /// *pending = false;
425 /// // We notify the condvar that the value has changed.
426 /// cvar.notify_one();
429 /// // wait for the thread to start up
430 /// let (lock, cvar) = &*pair;
431 /// let result = cvar.wait_timeout_while(
432 /// lock.lock().unwrap(),
433 /// Duration::from_millis(100),
434 /// |&mut pending| pending,
436 /// if result.1.timed_out() {
437 /// // timed-out without the condition ever evaluating to false.
439 /// // access the locked mutex via result.0
441 #[stable(feature = "wait_timeout_until", since = "1.42.0")]
442 pub fn wait_timeout_while<'a, T, F>(
444 mut guard: MutexGuard<'a, T>,
447 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
449 F: FnMut(&mut T) -> bool,
451 let start = Instant::now();
453 if !condition(&mut *guard) {
454 return Ok((guard, WaitTimeoutResult(false)));
456 let timeout = match dur.checked_sub(start.elapsed()) {
457 Some(timeout) => timeout,
458 None => return Ok((guard, WaitTimeoutResult(true))),
460 guard = self.wait_timeout(guard, timeout)?.0;
464 /// Wakes up one blocked thread on this condvar.
466 /// If there is a blocked thread on this condition variable, then it will
467 /// be woken up from its call to [`wait`] or [`wait_timeout`]. Calls to
468 /// `notify_one` are not buffered in any way.
470 /// To wake up all threads, see [`notify_all`].
472 /// [`wait`]: Self::wait
473 /// [`wait_timeout`]: Self::wait_timeout
474 /// [`notify_all`]: Self::notify_all
479 /// use std::sync::{Arc, Mutex, Condvar};
482 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
483 /// let pair2 = Arc::clone(&pair);
485 /// thread::spawn(move|| {
486 /// let (lock, cvar) = &*pair2;
487 /// let mut started = lock.lock().unwrap();
489 /// // We notify the condvar that the value has changed.
490 /// cvar.notify_one();
493 /// // Wait for the thread to start up.
494 /// let (lock, cvar) = &*pair;
495 /// let mut started = lock.lock().unwrap();
496 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
497 /// while !*started {
498 /// started = cvar.wait(started).unwrap();
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn notify_one(&self) {
503 self.inner.notify_one()
506 /// Wakes up all blocked threads on this condvar.
508 /// This method will ensure that any current waiters on the condition
509 /// variable are awoken. Calls to `notify_all()` are not buffered in any
512 /// To wake up only one thread, see [`notify_one`].
514 /// [`notify_one`]: Self::notify_one
519 /// use std::sync::{Arc, Mutex, Condvar};
522 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
523 /// let pair2 = Arc::clone(&pair);
525 /// thread::spawn(move|| {
526 /// let (lock, cvar) = &*pair2;
527 /// let mut started = lock.lock().unwrap();
529 /// // We notify the condvar that the value has changed.
530 /// cvar.notify_all();
533 /// // Wait for the thread to start up.
534 /// let (lock, cvar) = &*pair;
535 /// let mut started = lock.lock().unwrap();
536 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
537 /// while !*started {
538 /// started = cvar.wait(started).unwrap();
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn notify_all(&self) {
543 self.inner.notify_all()
547 #[stable(feature = "std_debug", since = "1.16.0")]
548 impl fmt::Debug for Condvar {
549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550 f.debug_struct("Condvar").finish_non_exhaustive()
554 #[stable(feature = "condvar_default", since = "1.10.0")]
555 impl Default for Condvar {
556 /// Creates a `Condvar` which is ready to be waited on and notified.
557 fn default() -> Condvar {