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")]
125 pub fn new() -> Condvar {
126 Condvar { inner: sys::Condvar::new() }
129 /// Blocks the current thread until this condition variable receives a
132 /// This function will atomically unlock the mutex specified (represented by
133 /// `guard`) and block the current thread. This means that any calls
134 /// to [`notify_one`] or [`notify_all`] which happen logically after the
135 /// mutex is unlocked are candidates to wake this thread up. When this
136 /// function call returns, the lock specified will have been re-acquired.
138 /// Note that this function is susceptible to spurious wakeups. Condition
139 /// variables normally have a boolean predicate associated with them, and
140 /// the predicate must always be checked each time this function returns to
141 /// protect against spurious wakeups.
145 /// This function will return an error if the mutex being waited on is
146 /// poisoned when this thread re-acquires the lock. For more information,
147 /// see information about [poisoning] on the [`Mutex`] type.
151 /// This function may [`panic!`] if it is used with more than one mutex
154 /// [`notify_one`]: Self::notify_one
155 /// [`notify_all`]: Self::notify_all
156 /// [poisoning]: super::Mutex#poisoning
157 /// [`Mutex`]: super::Mutex
162 /// use std::sync::{Arc, Mutex, Condvar};
165 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
166 /// let pair2 = Arc::clone(&pair);
168 /// thread::spawn(move|| {
169 /// let (lock, cvar) = &*pair2;
170 /// let mut started = lock.lock().unwrap();
172 /// // We notify the condvar that the value has changed.
173 /// cvar.notify_one();
176 /// // Wait for the thread to start up.
177 /// let (lock, cvar) = &*pair;
178 /// let mut started = lock.lock().unwrap();
179 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
180 /// while !*started {
181 /// started = cvar.wait(started).unwrap();
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
186 let poisoned = unsafe {
187 let lock = mutex::guard_lock(&guard);
188 self.inner.wait(lock);
189 mutex::guard_poison(&guard).get()
191 if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
194 /// Blocks the current thread until this condition variable receives a
195 /// notification and the provided condition is false.
197 /// This function will atomically unlock the mutex specified (represented by
198 /// `guard`) and block the current thread. This means that any calls
199 /// to [`notify_one`] or [`notify_all`] which happen logically after the
200 /// mutex is unlocked are candidates to wake this thread up. When this
201 /// function call returns, the lock specified will have been re-acquired.
205 /// This function will return an error if the mutex being waited on is
206 /// poisoned when this thread re-acquires the lock. For more information,
207 /// see information about [poisoning] on the [`Mutex`] type.
209 /// [`notify_one`]: Self::notify_one
210 /// [`notify_all`]: Self::notify_all
211 /// [poisoning]: super::Mutex#poisoning
212 /// [`Mutex`]: super::Mutex
217 /// use std::sync::{Arc, Mutex, Condvar};
220 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
221 /// let pair2 = Arc::clone(&pair);
223 /// thread::spawn(move|| {
224 /// let (lock, cvar) = &*pair2;
225 /// let mut pending = lock.lock().unwrap();
226 /// *pending = false;
227 /// // We notify the condvar that the value has changed.
228 /// cvar.notify_one();
231 /// // Wait for the thread to start up.
232 /// let (lock, cvar) = &*pair;
233 /// // As long as the value inside the `Mutex<bool>` is `true`, we wait.
234 /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
236 #[stable(feature = "wait_until", since = "1.42.0")]
237 pub fn wait_while<'a, T, F>(
239 mut guard: MutexGuard<'a, T>,
241 ) -> LockResult<MutexGuard<'a, T>>
243 F: FnMut(&mut T) -> bool,
245 while condition(&mut *guard) {
246 guard = self.wait(guard)?;
251 /// Waits on this condition variable for a notification, timing out after a
252 /// specified duration.
254 /// The semantics of this function are equivalent to [`wait`]
255 /// except that the thread will be blocked for roughly no longer
256 /// than `ms` milliseconds. This method should not be used for
257 /// precise timing due to anomalies such as preemption or platform
258 /// differences that might not cause the maximum amount of time
259 /// waited to be precisely `ms`.
261 /// Note that the best effort is made to ensure that the time waited is
262 /// measured with a monotonic clock, and not affected by the changes made to
265 /// The returned boolean is `false` only if the timeout is known
268 /// Like [`wait`], the lock specified will be re-acquired when this function
269 /// returns, regardless of whether the timeout elapsed or not.
271 /// [`wait`]: Self::wait
276 /// use std::sync::{Arc, Mutex, Condvar};
279 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
280 /// let pair2 = Arc::clone(&pair);
282 /// thread::spawn(move|| {
283 /// let (lock, cvar) = &*pair2;
284 /// let mut started = lock.lock().unwrap();
286 /// // We notify the condvar that the value has changed.
287 /// cvar.notify_one();
290 /// // Wait for the thread to start up.
291 /// let (lock, cvar) = &*pair;
292 /// let mut started = lock.lock().unwrap();
293 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
295 /// let result = cvar.wait_timeout_ms(started, 10).unwrap();
296 /// // 10 milliseconds have passed, or maybe the value changed!
297 /// started = result.0;
298 /// if *started == true {
299 /// // We received the notification and the value has been updated, we can leave.
304 #[stable(feature = "rust1", since = "1.0.0")]
305 #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::sync::Condvar::wait_timeout`")]
306 pub fn wait_timeout_ms<'a, T>(
308 guard: MutexGuard<'a, T>,
310 ) -> LockResult<(MutexGuard<'a, T>, bool)> {
311 let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
312 poison::map_result(res, |(a, b)| (a, !b.timed_out()))
315 /// Waits on this condition variable for a notification, timing out after a
316 /// specified duration.
318 /// The semantics of this function are equivalent to [`wait`] except that
319 /// the thread will be blocked for roughly no longer than `dur`. This
320 /// method should not be used for precise timing due to anomalies such as
321 /// preemption or platform differences that might not cause the maximum
322 /// amount of time waited to be precisely `dur`.
324 /// Note that the best effort is made to ensure that the time waited is
325 /// measured with a monotonic clock, and not affected by the changes made to
326 /// the system time. This function is susceptible to spurious wakeups.
327 /// Condition variables normally have a boolean predicate associated with
328 /// them, and the predicate must always be checked each time this function
329 /// returns to protect against spurious wakeups. Additionally, it is
330 /// typically desirable for the timeout to not exceed some duration in
331 /// spite of spurious wakes, thus the sleep-duration is decremented by the
332 /// amount slept. Alternatively, use the `wait_timeout_while` method
333 /// to wait with a timeout while a predicate is true.
335 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
336 /// known to have elapsed.
338 /// Like [`wait`], the lock specified will be re-acquired when this function
339 /// returns, regardless of whether the timeout elapsed or not.
341 /// [`wait`]: Self::wait
342 /// [`wait_timeout_while`]: Self::wait_timeout_while
347 /// use std::sync::{Arc, Mutex, Condvar};
349 /// use std::time::Duration;
351 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
352 /// let pair2 = Arc::clone(&pair);
354 /// thread::spawn(move|| {
355 /// let (lock, cvar) = &*pair2;
356 /// let mut started = lock.lock().unwrap();
358 /// // We notify the condvar that the value has changed.
359 /// cvar.notify_one();
362 /// // wait for the thread to start up
363 /// let (lock, cvar) = &*pair;
364 /// let mut started = lock.lock().unwrap();
365 /// // as long as the value inside the `Mutex<bool>` is `false`, we wait
367 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
368 /// // 10 milliseconds have passed, or maybe the value changed!
369 /// started = result.0;
370 /// if *started == true {
371 /// // We received the notification and the value has been updated, we can leave.
376 #[stable(feature = "wait_timeout", since = "1.5.0")]
377 pub fn wait_timeout<'a, T>(
379 guard: MutexGuard<'a, T>,
381 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
382 let (poisoned, result) = unsafe {
383 let lock = mutex::guard_lock(&guard);
384 let success = self.inner.wait_timeout(lock, dur);
385 (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
387 if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
390 /// Waits on this condition variable for a notification, timing out after a
391 /// specified duration.
393 /// The semantics of this function are equivalent to [`wait_while`] except
394 /// that the thread will be blocked for roughly no longer than `dur`. This
395 /// method should not be used for precise timing due to anomalies such as
396 /// preemption or platform differences that might not cause the maximum
397 /// amount of time waited to be precisely `dur`.
399 /// Note that the best effort is made to ensure that the time waited is
400 /// measured with a monotonic clock, and not affected by the changes made to
403 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
404 /// known to have elapsed without the condition being met.
406 /// Like [`wait_while`], the lock specified will be re-acquired when this
407 /// function returns, regardless of whether the timeout elapsed or not.
409 /// [`wait_while`]: Self::wait_while
410 /// [`wait_timeout`]: Self::wait_timeout
415 /// use std::sync::{Arc, Mutex, Condvar};
417 /// use std::time::Duration;
419 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
420 /// let pair2 = Arc::clone(&pair);
422 /// thread::spawn(move|| {
423 /// let (lock, cvar) = &*pair2;
424 /// let mut pending = lock.lock().unwrap();
425 /// *pending = false;
426 /// // We notify the condvar that the value has changed.
427 /// cvar.notify_one();
430 /// // wait for the thread to start up
431 /// let (lock, cvar) = &*pair;
432 /// let result = cvar.wait_timeout_while(
433 /// lock.lock().unwrap(),
434 /// Duration::from_millis(100),
435 /// |&mut pending| pending,
437 /// if result.1.timed_out() {
438 /// // timed-out without the condition ever evaluating to false.
440 /// // access the locked mutex via result.0
442 #[stable(feature = "wait_timeout_until", since = "1.42.0")]
443 pub fn wait_timeout_while<'a, T, F>(
445 mut guard: MutexGuard<'a, T>,
448 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
450 F: FnMut(&mut T) -> bool,
452 let start = Instant::now();
454 if !condition(&mut *guard) {
455 return Ok((guard, WaitTimeoutResult(false)));
457 let timeout = match dur.checked_sub(start.elapsed()) {
458 Some(timeout) => timeout,
459 None => return Ok((guard, WaitTimeoutResult(true))),
461 guard = self.wait_timeout(guard, timeout)?.0;
465 /// Wakes up one blocked thread on this condvar.
467 /// If there is a blocked thread on this condition variable, then it will
468 /// be woken up from its call to [`wait`] or [`wait_timeout`]. Calls to
469 /// `notify_one` are not buffered in any way.
471 /// To wake up all threads, see [`notify_all`].
473 /// [`wait`]: Self::wait
474 /// [`wait_timeout`]: Self::wait_timeout
475 /// [`notify_all`]: Self::notify_all
480 /// use std::sync::{Arc, Mutex, Condvar};
483 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
484 /// let pair2 = Arc::clone(&pair);
486 /// thread::spawn(move|| {
487 /// let (lock, cvar) = &*pair2;
488 /// let mut started = lock.lock().unwrap();
490 /// // We notify the condvar that the value has changed.
491 /// cvar.notify_one();
494 /// // Wait for the thread to start up.
495 /// let (lock, cvar) = &*pair;
496 /// let mut started = lock.lock().unwrap();
497 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
498 /// while !*started {
499 /// started = cvar.wait(started).unwrap();
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn notify_one(&self) {
504 self.inner.notify_one()
507 /// Wakes up all blocked threads on this condvar.
509 /// This method will ensure that any current waiters on the condition
510 /// variable are awoken. Calls to `notify_all()` are not buffered in any
513 /// To wake up only one thread, see [`notify_one`].
515 /// [`notify_one`]: Self::notify_one
520 /// use std::sync::{Arc, Mutex, Condvar};
523 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
524 /// let pair2 = Arc::clone(&pair);
526 /// thread::spawn(move|| {
527 /// let (lock, cvar) = &*pair2;
528 /// let mut started = lock.lock().unwrap();
530 /// // We notify the condvar that the value has changed.
531 /// cvar.notify_all();
534 /// // Wait for the thread to start up.
535 /// let (lock, cvar) = &*pair;
536 /// let mut started = lock.lock().unwrap();
537 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
538 /// while !*started {
539 /// started = cvar.wait(started).unwrap();
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub fn notify_all(&self) {
544 self.inner.notify_all()
548 #[stable(feature = "std_debug", since = "1.16.0")]
549 impl fmt::Debug for Condvar {
550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551 f.debug_struct("Condvar").finish_non_exhaustive()
555 #[stable(feature = "condvar_default", since = "1.10.0")]
556 impl Default for Condvar {
557 /// Creates a `Condvar` which is ready to be waited on and notified.
558 fn default() -> Condvar {