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.
65 #[stable(feature = "wait_timeout", since = "1.5.0")]
66 pub fn timed_out(&self) -> bool {
71 /// A Condition Variable
73 /// Condition variables represent the ability to block a thread such that it
74 /// consumes no CPU time while waiting for an event to occur. Condition
75 /// variables are typically associated with a boolean predicate (a condition)
76 /// and a mutex. The predicate is always verified inside of the mutex before
77 /// determining that a thread must block.
79 /// Functions in this module will block the current **thread** of execution.
80 /// Note that any attempt to use multiple mutexes on the same condition
81 /// variable may result in a runtime panic.
86 /// use std::sync::{Arc, Mutex, Condvar};
89 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
90 /// let pair2 = Arc::clone(&pair);
92 /// // Inside of our lock, spawn a new thread, and then wait for it to start.
93 /// thread::spawn(move|| {
94 /// let (lock, cvar) = &*pair2;
95 /// let mut started = lock.lock().unwrap();
97 /// // We notify the condvar that the value has changed.
98 /// cvar.notify_one();
101 /// // Wait for the thread to start up.
102 /// let (lock, cvar) = &*pair;
103 /// let mut started = lock.lock().unwrap();
104 /// while !*started {
105 /// started = cvar.wait(started).unwrap();
108 #[stable(feature = "rust1", since = "1.0.0")]
114 /// Creates a new condition variable which is ready to be waited on and
120 /// use std::sync::Condvar;
122 /// let condvar = Condvar::new();
124 #[stable(feature = "rust1", since = "1.0.0")]
125 #[rustc_const_stable(feature = "const_locks", since = "1.63.0")]
128 pub const fn new() -> Condvar {
129 Condvar { inner: sys::Condvar::new() }
132 /// Blocks the current thread until this condition variable receives a
135 /// This function will atomically unlock the mutex specified (represented by
136 /// `guard`) and block the current thread. This means that any calls
137 /// to [`notify_one`] or [`notify_all`] which happen logically after the
138 /// mutex is unlocked are candidates to wake this thread up. When this
139 /// function call returns, the lock specified will have been re-acquired.
141 /// Note that this function is susceptible to spurious wakeups. Condition
142 /// variables normally have a boolean predicate associated with them, and
143 /// the predicate must always be checked each time this function returns to
144 /// protect against spurious wakeups.
148 /// This function will return an error if the mutex being waited on is
149 /// poisoned when this thread re-acquires the lock. For more information,
150 /// see information about [poisoning] on the [`Mutex`] type.
154 /// This function may [`panic!`] if it is used with more than one mutex
157 /// [`notify_one`]: Self::notify_one
158 /// [`notify_all`]: Self::notify_all
159 /// [poisoning]: super::Mutex#poisoning
160 /// [`Mutex`]: super::Mutex
165 /// use std::sync::{Arc, Mutex, Condvar};
168 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
169 /// let pair2 = Arc::clone(&pair);
171 /// thread::spawn(move|| {
172 /// let (lock, cvar) = &*pair2;
173 /// let mut started = lock.lock().unwrap();
175 /// // We notify the condvar that the value has changed.
176 /// cvar.notify_one();
179 /// // Wait for the thread to start up.
180 /// let (lock, cvar) = &*pair;
181 /// let mut started = lock.lock().unwrap();
182 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
183 /// while !*started {
184 /// started = cvar.wait(started).unwrap();
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
189 let poisoned = unsafe {
190 let lock = mutex::guard_lock(&guard);
191 self.inner.wait(lock);
192 mutex::guard_poison(&guard).get()
194 if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
197 /// Blocks the current thread until this condition variable receives a
198 /// notification and the provided condition is false.
200 /// This function will atomically unlock the mutex specified (represented by
201 /// `guard`) and block the current thread. This means that any calls
202 /// to [`notify_one`] or [`notify_all`] which happen logically after the
203 /// mutex is unlocked are candidates to wake this thread up. When this
204 /// function call returns, the lock specified will have been re-acquired.
208 /// This function will return an error if the mutex being waited on is
209 /// poisoned when this thread re-acquires the lock. For more information,
210 /// see information about [poisoning] on the [`Mutex`] type.
212 /// [`notify_one`]: Self::notify_one
213 /// [`notify_all`]: Self::notify_all
214 /// [poisoning]: super::Mutex#poisoning
215 /// [`Mutex`]: super::Mutex
220 /// use std::sync::{Arc, Mutex, Condvar};
223 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
224 /// let pair2 = Arc::clone(&pair);
226 /// thread::spawn(move|| {
227 /// let (lock, cvar) = &*pair2;
228 /// let mut pending = lock.lock().unwrap();
229 /// *pending = false;
230 /// // We notify the condvar that the value has changed.
231 /// cvar.notify_one();
234 /// // Wait for the thread to start up.
235 /// let (lock, cvar) = &*pair;
236 /// // As long as the value inside the `Mutex<bool>` is `true`, we wait.
237 /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
239 #[stable(feature = "wait_until", since = "1.42.0")]
240 pub fn wait_while<'a, T, F>(
242 mut guard: MutexGuard<'a, T>,
244 ) -> LockResult<MutexGuard<'a, T>>
246 F: FnMut(&mut T) -> bool,
248 while condition(&mut *guard) {
249 guard = self.wait(guard)?;
254 /// Waits on this condition variable for a notification, timing out after a
255 /// specified duration.
257 /// The semantics of this function are equivalent to [`wait`]
258 /// except that the thread will be blocked for roughly no longer
259 /// than `ms` milliseconds. This method should not be used for
260 /// precise timing due to anomalies such as preemption or platform
261 /// differences that might not cause the maximum amount of time
262 /// waited to be precisely `ms`.
264 /// Note that the best effort is made to ensure that the time waited is
265 /// measured with a monotonic clock, and not affected by the changes made to
268 /// The returned boolean is `false` only if the timeout is known
271 /// Like [`wait`], the lock specified will be re-acquired when this function
272 /// returns, regardless of whether the timeout elapsed or not.
274 /// [`wait`]: Self::wait
279 /// use std::sync::{Arc, Mutex, Condvar};
282 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
283 /// let pair2 = Arc::clone(&pair);
285 /// thread::spawn(move|| {
286 /// let (lock, cvar) = &*pair2;
287 /// let mut started = lock.lock().unwrap();
289 /// // We notify the condvar that the value has changed.
290 /// cvar.notify_one();
293 /// // Wait for the thread to start up.
294 /// let (lock, cvar) = &*pair;
295 /// let mut started = lock.lock().unwrap();
296 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
298 /// let result = cvar.wait_timeout_ms(started, 10).unwrap();
299 /// // 10 milliseconds have passed, or maybe the value changed!
300 /// started = result.0;
301 /// if *started == true {
302 /// // We received the notification and the value has been updated, we can leave.
307 #[stable(feature = "rust1", since = "1.0.0")]
308 #[deprecated(since = "1.6.0", note = "replaced by `std::sync::Condvar::wait_timeout`")]
309 pub fn wait_timeout_ms<'a, T>(
311 guard: MutexGuard<'a, T>,
313 ) -> LockResult<(MutexGuard<'a, T>, bool)> {
314 let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
315 poison::map_result(res, |(a, b)| (a, !b.timed_out()))
318 /// Waits on this condition variable for a notification, timing out after a
319 /// specified duration.
321 /// The semantics of this function are equivalent to [`wait`] except that
322 /// the thread will be blocked for roughly no longer than `dur`. This
323 /// method should not be used for precise timing due to anomalies such as
324 /// preemption or platform differences that might not cause the maximum
325 /// amount of time waited to be precisely `dur`.
327 /// Note that the best effort is made to ensure that the time waited is
328 /// measured with a monotonic clock, and not affected by the changes made to
329 /// the system time. This function is susceptible to spurious wakeups.
330 /// Condition variables normally have a boolean predicate associated with
331 /// them, and the predicate must always be checked each time this function
332 /// returns to protect against spurious wakeups. Additionally, it is
333 /// typically desirable for the timeout to not exceed some duration in
334 /// spite of spurious wakes, thus the sleep-duration is decremented by the
335 /// amount slept. Alternatively, use the `wait_timeout_while` method
336 /// to wait with a timeout while a predicate is true.
338 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
339 /// known to have elapsed.
341 /// Like [`wait`], the lock specified will be re-acquired when this function
342 /// returns, regardless of whether the timeout elapsed or not.
344 /// [`wait`]: Self::wait
345 /// [`wait_timeout_while`]: Self::wait_timeout_while
350 /// use std::sync::{Arc, Mutex, Condvar};
352 /// use std::time::Duration;
354 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
355 /// let pair2 = Arc::clone(&pair);
357 /// thread::spawn(move|| {
358 /// let (lock, cvar) = &*pair2;
359 /// let mut started = lock.lock().unwrap();
361 /// // We notify the condvar that the value has changed.
362 /// cvar.notify_one();
365 /// // wait for the thread to start up
366 /// let (lock, cvar) = &*pair;
367 /// let mut started = lock.lock().unwrap();
368 /// // as long as the value inside the `Mutex<bool>` is `false`, we wait
370 /// let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
371 /// // 10 milliseconds have passed, or maybe the value changed!
372 /// started = result.0;
373 /// if *started == true {
374 /// // We received the notification and the value has been updated, we can leave.
379 #[stable(feature = "wait_timeout", since = "1.5.0")]
380 pub fn wait_timeout<'a, T>(
382 guard: MutexGuard<'a, T>,
384 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
385 let (poisoned, result) = unsafe {
386 let lock = mutex::guard_lock(&guard);
387 let success = self.inner.wait_timeout(lock, dur);
388 (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
390 if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
393 /// Waits on this condition variable for a notification, timing out after a
394 /// specified duration.
396 /// The semantics of this function are equivalent to [`wait_while`] except
397 /// that the thread will be blocked for roughly no longer than `dur`. This
398 /// method should not be used for precise timing due to anomalies such as
399 /// preemption or platform differences that might not cause the maximum
400 /// amount of time waited to be precisely `dur`.
402 /// Note that the best effort is made to ensure that the time waited is
403 /// measured with a monotonic clock, and not affected by the changes made to
406 /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
407 /// known to have elapsed without the condition being met.
409 /// Like [`wait_while`], the lock specified will be re-acquired when this
410 /// function returns, regardless of whether the timeout elapsed or not.
412 /// [`wait_while`]: Self::wait_while
413 /// [`wait_timeout`]: Self::wait_timeout
418 /// use std::sync::{Arc, Mutex, Condvar};
420 /// use std::time::Duration;
422 /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
423 /// let pair2 = Arc::clone(&pair);
425 /// thread::spawn(move|| {
426 /// let (lock, cvar) = &*pair2;
427 /// let mut pending = lock.lock().unwrap();
428 /// *pending = false;
429 /// // We notify the condvar that the value has changed.
430 /// cvar.notify_one();
433 /// // wait for the thread to start up
434 /// let (lock, cvar) = &*pair;
435 /// let result = cvar.wait_timeout_while(
436 /// lock.lock().unwrap(),
437 /// Duration::from_millis(100),
438 /// |&mut pending| pending,
440 /// if result.1.timed_out() {
441 /// // timed-out without the condition ever evaluating to false.
443 /// // access the locked mutex via result.0
445 #[stable(feature = "wait_timeout_until", since = "1.42.0")]
446 pub fn wait_timeout_while<'a, T, F>(
448 mut guard: MutexGuard<'a, T>,
451 ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
453 F: FnMut(&mut T) -> bool,
455 let start = Instant::now();
457 if !condition(&mut *guard) {
458 return Ok((guard, WaitTimeoutResult(false)));
460 let timeout = match dur.checked_sub(start.elapsed()) {
461 Some(timeout) => timeout,
462 None => return Ok((guard, WaitTimeoutResult(true))),
464 guard = self.wait_timeout(guard, timeout)?.0;
468 /// Wakes up one blocked thread on this condvar.
470 /// If there is a blocked thread on this condition variable, then it will
471 /// be woken up from its call to [`wait`] or [`wait_timeout`]. Calls to
472 /// `notify_one` are not buffered in any way.
474 /// To wake up all threads, see [`notify_all`].
476 /// [`wait`]: Self::wait
477 /// [`wait_timeout`]: Self::wait_timeout
478 /// [`notify_all`]: Self::notify_all
483 /// use std::sync::{Arc, Mutex, Condvar};
486 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
487 /// let pair2 = Arc::clone(&pair);
489 /// thread::spawn(move|| {
490 /// let (lock, cvar) = &*pair2;
491 /// let mut started = lock.lock().unwrap();
493 /// // We notify the condvar that the value has changed.
494 /// cvar.notify_one();
497 /// // Wait for the thread to start up.
498 /// let (lock, cvar) = &*pair;
499 /// let mut started = lock.lock().unwrap();
500 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
501 /// while !*started {
502 /// started = cvar.wait(started).unwrap();
505 #[stable(feature = "rust1", since = "1.0.0")]
506 pub fn notify_one(&self) {
507 self.inner.notify_one()
510 /// Wakes up all blocked threads on this condvar.
512 /// This method will ensure that any current waiters on the condition
513 /// variable are awoken. Calls to `notify_all()` are not buffered in any
516 /// To wake up only one thread, see [`notify_one`].
518 /// [`notify_one`]: Self::notify_one
523 /// use std::sync::{Arc, Mutex, Condvar};
526 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
527 /// let pair2 = Arc::clone(&pair);
529 /// thread::spawn(move|| {
530 /// let (lock, cvar) = &*pair2;
531 /// let mut started = lock.lock().unwrap();
533 /// // We notify the condvar that the value has changed.
534 /// cvar.notify_all();
537 /// // Wait for the thread to start up.
538 /// let (lock, cvar) = &*pair;
539 /// let mut started = lock.lock().unwrap();
540 /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
541 /// while !*started {
542 /// started = cvar.wait(started).unwrap();
545 #[stable(feature = "rust1", since = "1.0.0")]
546 pub fn notify_all(&self) {
547 self.inner.notify_all()
551 #[stable(feature = "std_debug", since = "1.16.0")]
552 impl fmt::Debug for Condvar {
553 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 f.debug_struct("Condvar").finish_non_exhaustive()
558 #[stable(feature = "condvar_default", since = "1.10.0")]
559 impl Default for Condvar {
560 /// Creates a `Condvar` which is ready to be waited on and notified.
561 fn default() -> Condvar {