]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/condvar.rs
Auto merge of #101228 - nnethercote:simplify-hir-PathSegment, r=petrochenkov
[rust.git] / library / std / src / sync / condvar.rs
1 #[cfg(test)]
2 mod tests;
3
4 use crate::fmt;
5 use crate::sync::{mutex, poison, LockResult, MutexGuard, PoisonError};
6 use crate::sys_common::condvar as sys;
7 use crate::time::{Duration, Instant};
8
9 /// A type indicating whether a timed wait on a condition variable returned
10 /// due to a time out or not.
11 ///
12 /// It is returned by the [`wait_timeout`] method.
13 ///
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);
18
19 impl WaitTimeoutResult {
20     /// Returns `true` if the wait was known to have timed out.
21     ///
22     /// # Examples
23     ///
24     /// This example spawns a thread which will update the boolean value and
25     /// then wait 100 milliseconds before notifying the condvar.
26     ///
27     /// The main thread will wait with a timeout on the condvar and then leave
28     /// once the boolean has been updated and notified.
29     ///
30     /// ```
31     /// use std::sync::{Arc, Condvar, Mutex};
32     /// use std::thread;
33     /// use std::time::Duration;
34     ///
35     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
36     /// let pair2 = Arc::clone(&pair);
37     ///
38     /// thread::spawn(move || {
39     ///     let (lock, cvar) = &*pair2;
40     ///
41     ///     // Let's wait 20 milliseconds before notifying the condvar.
42     ///     thread::sleep(Duration::from_millis(20));
43     ///
44     ///     let mut started = lock.lock().unwrap();
45     ///     // We update the boolean value.
46     ///     *started = true;
47     ///     cvar.notify_one();
48     /// });
49     ///
50     /// // Wait for the thread to start up.
51     /// let (lock, cvar) = &*pair;
52     /// let mut started = lock.lock().unwrap();
53     /// loop {
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.
60     ///         break
61     ///     }
62     /// }
63     /// ```
64     #[must_use]
65     #[stable(feature = "wait_timeout", since = "1.5.0")]
66     pub fn timed_out(&self) -> bool {
67         self.0
68     }
69 }
70
71 /// A Condition Variable
72 ///
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.
78 ///
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.
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// use std::sync::{Arc, Mutex, Condvar};
87 /// use std::thread;
88 ///
89 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
90 /// let pair2 = Arc::clone(&pair);
91 ///
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();
96 ///     *started = true;
97 ///     // We notify the condvar that the value has changed.
98 ///     cvar.notify_one();
99 /// });
100 ///
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();
106 /// }
107 /// ```
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub struct Condvar {
110     inner: sys::Condvar,
111 }
112
113 impl Condvar {
114     /// Creates a new condition variable which is ready to be waited on and
115     /// notified.
116     ///
117     /// # Examples
118     ///
119     /// ```
120     /// use std::sync::Condvar;
121     ///
122     /// let condvar = Condvar::new();
123     /// ```
124     #[stable(feature = "rust1", since = "1.0.0")]
125     #[rustc_const_stable(feature = "const_locks", since = "1.63.0")]
126     #[must_use]
127     #[inline]
128     pub const fn new() -> Condvar {
129         Condvar { inner: sys::Condvar::new() }
130     }
131
132     /// Blocks the current thread until this condition variable receives a
133     /// notification.
134     ///
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.
140     ///
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.
145     ///
146     /// # Errors
147     ///
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.
151     ///
152     /// # Panics
153     ///
154     /// This function may [`panic!`] if it is used with more than one mutex
155     /// over time.
156     ///
157     /// [`notify_one`]: Self::notify_one
158     /// [`notify_all`]: Self::notify_all
159     /// [poisoning]: super::Mutex#poisoning
160     /// [`Mutex`]: super::Mutex
161     ///
162     /// # Examples
163     ///
164     /// ```
165     /// use std::sync::{Arc, Mutex, Condvar};
166     /// use std::thread;
167     ///
168     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
169     /// let pair2 = Arc::clone(&pair);
170     ///
171     /// thread::spawn(move|| {
172     ///     let (lock, cvar) = &*pair2;
173     ///     let mut started = lock.lock().unwrap();
174     ///     *started = true;
175     ///     // We notify the condvar that the value has changed.
176     ///     cvar.notify_one();
177     /// });
178     ///
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();
185     /// }
186     /// ```
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()
193         };
194         if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
195     }
196
197     /// Blocks the current thread until this condition variable receives a
198     /// notification and the provided condition is false.
199     ///
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.
205     ///
206     /// # Errors
207     ///
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.
211     ///
212     /// [`notify_one`]: Self::notify_one
213     /// [`notify_all`]: Self::notify_all
214     /// [poisoning]: super::Mutex#poisoning
215     /// [`Mutex`]: super::Mutex
216     ///
217     /// # Examples
218     ///
219     /// ```
220     /// use std::sync::{Arc, Mutex, Condvar};
221     /// use std::thread;
222     ///
223     /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
224     /// let pair2 = Arc::clone(&pair);
225     ///
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();
232     /// });
233     ///
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();
238     /// ```
239     #[stable(feature = "wait_until", since = "1.42.0")]
240     pub fn wait_while<'a, T, F>(
241         &self,
242         mut guard: MutexGuard<'a, T>,
243         mut condition: F,
244     ) -> LockResult<MutexGuard<'a, T>>
245     where
246         F: FnMut(&mut T) -> bool,
247     {
248         while condition(&mut *guard) {
249             guard = self.wait(guard)?;
250         }
251         Ok(guard)
252     }
253
254     /// Waits on this condition variable for a notification, timing out after a
255     /// specified duration.
256     ///
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`.
263     ///
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
266     /// the system time.
267     ///
268     /// The returned boolean is `false` only if the timeout is known
269     /// to have elapsed.
270     ///
271     /// Like [`wait`], the lock specified will be re-acquired when this function
272     /// returns, regardless of whether the timeout elapsed or not.
273     ///
274     /// [`wait`]: Self::wait
275     ///
276     /// # Examples
277     ///
278     /// ```
279     /// use std::sync::{Arc, Mutex, Condvar};
280     /// use std::thread;
281     ///
282     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
283     /// let pair2 = Arc::clone(&pair);
284     ///
285     /// thread::spawn(move|| {
286     ///     let (lock, cvar) = &*pair2;
287     ///     let mut started = lock.lock().unwrap();
288     ///     *started = true;
289     ///     // We notify the condvar that the value has changed.
290     ///     cvar.notify_one();
291     /// });
292     ///
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.
297     /// loop {
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.
303     ///         break
304     ///     }
305     /// }
306     /// ```
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>(
310         &self,
311         guard: MutexGuard<'a, T>,
312         ms: u32,
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()))
316     }
317
318     /// Waits on this condition variable for a notification, timing out after a
319     /// specified duration.
320     ///
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`.
326     ///
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.
337     ///
338     /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
339     /// known to have elapsed.
340     ///
341     /// Like [`wait`], the lock specified will be re-acquired when this function
342     /// returns, regardless of whether the timeout elapsed or not.
343     ///
344     /// [`wait`]: Self::wait
345     /// [`wait_timeout_while`]: Self::wait_timeout_while
346     ///
347     /// # Examples
348     ///
349     /// ```
350     /// use std::sync::{Arc, Mutex, Condvar};
351     /// use std::thread;
352     /// use std::time::Duration;
353     ///
354     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
355     /// let pair2 = Arc::clone(&pair);
356     ///
357     /// thread::spawn(move|| {
358     ///     let (lock, cvar) = &*pair2;
359     ///     let mut started = lock.lock().unwrap();
360     ///     *started = true;
361     ///     // We notify the condvar that the value has changed.
362     ///     cvar.notify_one();
363     /// });
364     ///
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
369     /// loop {
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.
375     ///         break
376     ///     }
377     /// }
378     /// ```
379     #[stable(feature = "wait_timeout", since = "1.5.0")]
380     pub fn wait_timeout<'a, T>(
381         &self,
382         guard: MutexGuard<'a, T>,
383         dur: Duration,
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))
389         };
390         if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
391     }
392
393     /// Waits on this condition variable for a notification, timing out after a
394     /// specified duration.
395     ///
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`.
401     ///
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
404     /// the system time.
405     ///
406     /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
407     /// known to have elapsed without the condition being met.
408     ///
409     /// Like [`wait_while`], the lock specified will be re-acquired when this
410     /// function returns, regardless of whether the timeout elapsed or not.
411     ///
412     /// [`wait_while`]: Self::wait_while
413     /// [`wait_timeout`]: Self::wait_timeout
414     ///
415     /// # Examples
416     ///
417     /// ```
418     /// use std::sync::{Arc, Mutex, Condvar};
419     /// use std::thread;
420     /// use std::time::Duration;
421     ///
422     /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
423     /// let pair2 = Arc::clone(&pair);
424     ///
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();
431     /// });
432     ///
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,
439     /// ).unwrap();
440     /// if result.1.timed_out() {
441     ///     // timed-out without the condition ever evaluating to false.
442     /// }
443     /// // access the locked mutex via result.0
444     /// ```
445     #[stable(feature = "wait_timeout_until", since = "1.42.0")]
446     pub fn wait_timeout_while<'a, T, F>(
447         &self,
448         mut guard: MutexGuard<'a, T>,
449         dur: Duration,
450         mut condition: F,
451     ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
452     where
453         F: FnMut(&mut T) -> bool,
454     {
455         let start = Instant::now();
456         loop {
457             if !condition(&mut *guard) {
458                 return Ok((guard, WaitTimeoutResult(false)));
459             }
460             let timeout = match dur.checked_sub(start.elapsed()) {
461                 Some(timeout) => timeout,
462                 None => return Ok((guard, WaitTimeoutResult(true))),
463             };
464             guard = self.wait_timeout(guard, timeout)?.0;
465         }
466     }
467
468     /// Wakes up one blocked thread on this condvar.
469     ///
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.
473     ///
474     /// To wake up all threads, see [`notify_all`].
475     ///
476     /// [`wait`]: Self::wait
477     /// [`wait_timeout`]: Self::wait_timeout
478     /// [`notify_all`]: Self::notify_all
479     ///
480     /// # Examples
481     ///
482     /// ```
483     /// use std::sync::{Arc, Mutex, Condvar};
484     /// use std::thread;
485     ///
486     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
487     /// let pair2 = Arc::clone(&pair);
488     ///
489     /// thread::spawn(move|| {
490     ///     let (lock, cvar) = &*pair2;
491     ///     let mut started = lock.lock().unwrap();
492     ///     *started = true;
493     ///     // We notify the condvar that the value has changed.
494     ///     cvar.notify_one();
495     /// });
496     ///
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();
503     /// }
504     /// ```
505     #[stable(feature = "rust1", since = "1.0.0")]
506     pub fn notify_one(&self) {
507         self.inner.notify_one()
508     }
509
510     /// Wakes up all blocked threads on this condvar.
511     ///
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
514     /// way.
515     ///
516     /// To wake up only one thread, see [`notify_one`].
517     ///
518     /// [`notify_one`]: Self::notify_one
519     ///
520     /// # Examples
521     ///
522     /// ```
523     /// use std::sync::{Arc, Mutex, Condvar};
524     /// use std::thread;
525     ///
526     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
527     /// let pair2 = Arc::clone(&pair);
528     ///
529     /// thread::spawn(move|| {
530     ///     let (lock, cvar) = &*pair2;
531     ///     let mut started = lock.lock().unwrap();
532     ///     *started = true;
533     ///     // We notify the condvar that the value has changed.
534     ///     cvar.notify_all();
535     /// });
536     ///
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();
543     /// }
544     /// ```
545     #[stable(feature = "rust1", since = "1.0.0")]
546     pub fn notify_all(&self) {
547         self.inner.notify_all()
548     }
549 }
550
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()
555     }
556 }
557
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 {
562         Condvar::new()
563     }
564 }