]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/condvar.rs
Rollup merge of #89730 - crlf0710:type_changing_feature, r=jackh726
[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     #[stable(feature = "wait_timeout", since = "1.5.0")]
65     pub fn timed_out(&self) -> bool {
66         self.0
67     }
68 }
69
70 /// A Condition Variable
71 ///
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.
77 ///
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.
81 ///
82 /// # Examples
83 ///
84 /// ```
85 /// use std::sync::{Arc, Mutex, Condvar};
86 /// use std::thread;
87 ///
88 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
89 /// let pair2 = Arc::clone(&pair);
90 ///
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();
95 ///     *started = true;
96 ///     // We notify the condvar that the value has changed.
97 ///     cvar.notify_one();
98 /// });
99 ///
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();
105 /// }
106 /// ```
107 #[stable(feature = "rust1", since = "1.0.0")]
108 pub struct Condvar {
109     inner: sys::Condvar,
110 }
111
112 impl Condvar {
113     /// Creates a new condition variable which is ready to be waited on and
114     /// notified.
115     ///
116     /// # Examples
117     ///
118     /// ```
119     /// use std::sync::Condvar;
120     ///
121     /// let condvar = Condvar::new();
122     /// ```
123     #[stable(feature = "rust1", since = "1.0.0")]
124     #[must_use]
125     pub fn new() -> Condvar {
126         Condvar { inner: sys::Condvar::new() }
127     }
128
129     /// Blocks the current thread until this condition variable receives a
130     /// notification.
131     ///
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.
137     ///
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.
142     ///
143     /// # Errors
144     ///
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.
148     ///
149     /// # Panics
150     ///
151     /// This function may [`panic!`] if it is used with more than one mutex
152     /// over time.
153     ///
154     /// [`notify_one`]: Self::notify_one
155     /// [`notify_all`]: Self::notify_all
156     /// [poisoning]: super::Mutex#poisoning
157     /// [`Mutex`]: super::Mutex
158     ///
159     /// # Examples
160     ///
161     /// ```
162     /// use std::sync::{Arc, Mutex, Condvar};
163     /// use std::thread;
164     ///
165     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
166     /// let pair2 = Arc::clone(&pair);
167     ///
168     /// thread::spawn(move|| {
169     ///     let (lock, cvar) = &*pair2;
170     ///     let mut started = lock.lock().unwrap();
171     ///     *started = true;
172     ///     // We notify the condvar that the value has changed.
173     ///     cvar.notify_one();
174     /// });
175     ///
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();
182     /// }
183     /// ```
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()
190         };
191         if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
192     }
193
194     /// Blocks the current thread until this condition variable receives a
195     /// notification and the provided condition is false.
196     ///
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.
202     ///
203     /// # Errors
204     ///
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.
208     ///
209     /// [`notify_one`]: Self::notify_one
210     /// [`notify_all`]: Self::notify_all
211     /// [poisoning]: super::Mutex#poisoning
212     /// [`Mutex`]: super::Mutex
213     ///
214     /// # Examples
215     ///
216     /// ```
217     /// use std::sync::{Arc, Mutex, Condvar};
218     /// use std::thread;
219     ///
220     /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
221     /// let pair2 = Arc::clone(&pair);
222     ///
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();
229     /// });
230     ///
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();
235     /// ```
236     #[stable(feature = "wait_until", since = "1.42.0")]
237     pub fn wait_while<'a, T, F>(
238         &self,
239         mut guard: MutexGuard<'a, T>,
240         mut condition: F,
241     ) -> LockResult<MutexGuard<'a, T>>
242     where
243         F: FnMut(&mut T) -> bool,
244     {
245         while condition(&mut *guard) {
246             guard = self.wait(guard)?;
247         }
248         Ok(guard)
249     }
250
251     /// Waits on this condition variable for a notification, timing out after a
252     /// specified duration.
253     ///
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`.
260     ///
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
263     /// the system time.
264     ///
265     /// The returned boolean is `false` only if the timeout is known
266     /// to have elapsed.
267     ///
268     /// Like [`wait`], the lock specified will be re-acquired when this function
269     /// returns, regardless of whether the timeout elapsed or not.
270     ///
271     /// [`wait`]: Self::wait
272     ///
273     /// # Examples
274     ///
275     /// ```
276     /// use std::sync::{Arc, Mutex, Condvar};
277     /// use std::thread;
278     ///
279     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
280     /// let pair2 = Arc::clone(&pair);
281     ///
282     /// thread::spawn(move|| {
283     ///     let (lock, cvar) = &*pair2;
284     ///     let mut started = lock.lock().unwrap();
285     ///     *started = true;
286     ///     // We notify the condvar that the value has changed.
287     ///     cvar.notify_one();
288     /// });
289     ///
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.
294     /// loop {
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.
300     ///         break
301     ///     }
302     /// }
303     /// ```
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>(
307         &self,
308         guard: MutexGuard<'a, T>,
309         ms: u32,
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()))
313     }
314
315     /// Waits on this condition variable for a notification, timing out after a
316     /// specified duration.
317     ///
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`.
323     ///
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.
334     ///
335     /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
336     /// known to have elapsed.
337     ///
338     /// Like [`wait`], the lock specified will be re-acquired when this function
339     /// returns, regardless of whether the timeout elapsed or not.
340     ///
341     /// [`wait`]: Self::wait
342     /// [`wait_timeout_while`]: Self::wait_timeout_while
343     ///
344     /// # Examples
345     ///
346     /// ```
347     /// use std::sync::{Arc, Mutex, Condvar};
348     /// use std::thread;
349     /// use std::time::Duration;
350     ///
351     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
352     /// let pair2 = Arc::clone(&pair);
353     ///
354     /// thread::spawn(move|| {
355     ///     let (lock, cvar) = &*pair2;
356     ///     let mut started = lock.lock().unwrap();
357     ///     *started = true;
358     ///     // We notify the condvar that the value has changed.
359     ///     cvar.notify_one();
360     /// });
361     ///
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
366     /// loop {
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.
372     ///         break
373     ///     }
374     /// }
375     /// ```
376     #[stable(feature = "wait_timeout", since = "1.5.0")]
377     pub fn wait_timeout<'a, T>(
378         &self,
379         guard: MutexGuard<'a, T>,
380         dur: Duration,
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))
386         };
387         if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
388     }
389
390     /// Waits on this condition variable for a notification, timing out after a
391     /// specified duration.
392     ///
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`.
398     ///
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
401     /// the system time.
402     ///
403     /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
404     /// known to have elapsed without the condition being met.
405     ///
406     /// Like [`wait_while`], the lock specified will be re-acquired when this
407     /// function returns, regardless of whether the timeout elapsed or not.
408     ///
409     /// [`wait_while`]: Self::wait_while
410     /// [`wait_timeout`]: Self::wait_timeout
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// use std::sync::{Arc, Mutex, Condvar};
416     /// use std::thread;
417     /// use std::time::Duration;
418     ///
419     /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
420     /// let pair2 = Arc::clone(&pair);
421     ///
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();
428     /// });
429     ///
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,
436     /// ).unwrap();
437     /// if result.1.timed_out() {
438     ///     // timed-out without the condition ever evaluating to false.
439     /// }
440     /// // access the locked mutex via result.0
441     /// ```
442     #[stable(feature = "wait_timeout_until", since = "1.42.0")]
443     pub fn wait_timeout_while<'a, T, F>(
444         &self,
445         mut guard: MutexGuard<'a, T>,
446         dur: Duration,
447         mut condition: F,
448     ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
449     where
450         F: FnMut(&mut T) -> bool,
451     {
452         let start = Instant::now();
453         loop {
454             if !condition(&mut *guard) {
455                 return Ok((guard, WaitTimeoutResult(false)));
456             }
457             let timeout = match dur.checked_sub(start.elapsed()) {
458                 Some(timeout) => timeout,
459                 None => return Ok((guard, WaitTimeoutResult(true))),
460             };
461             guard = self.wait_timeout(guard, timeout)?.0;
462         }
463     }
464
465     /// Wakes up one blocked thread on this condvar.
466     ///
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.
470     ///
471     /// To wake up all threads, see [`notify_all`].
472     ///
473     /// [`wait`]: Self::wait
474     /// [`wait_timeout`]: Self::wait_timeout
475     /// [`notify_all`]: Self::notify_all
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// use std::sync::{Arc, Mutex, Condvar};
481     /// use std::thread;
482     ///
483     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
484     /// let pair2 = Arc::clone(&pair);
485     ///
486     /// thread::spawn(move|| {
487     ///     let (lock, cvar) = &*pair2;
488     ///     let mut started = lock.lock().unwrap();
489     ///     *started = true;
490     ///     // We notify the condvar that the value has changed.
491     ///     cvar.notify_one();
492     /// });
493     ///
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();
500     /// }
501     /// ```
502     #[stable(feature = "rust1", since = "1.0.0")]
503     pub fn notify_one(&self) {
504         self.inner.notify_one()
505     }
506
507     /// Wakes up all blocked threads on this condvar.
508     ///
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
511     /// way.
512     ///
513     /// To wake up only one thread, see [`notify_one`].
514     ///
515     /// [`notify_one`]: Self::notify_one
516     ///
517     /// # Examples
518     ///
519     /// ```
520     /// use std::sync::{Arc, Mutex, Condvar};
521     /// use std::thread;
522     ///
523     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
524     /// let pair2 = Arc::clone(&pair);
525     ///
526     /// thread::spawn(move|| {
527     ///     let (lock, cvar) = &*pair2;
528     ///     let mut started = lock.lock().unwrap();
529     ///     *started = true;
530     ///     // We notify the condvar that the value has changed.
531     ///     cvar.notify_all();
532     /// });
533     ///
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();
540     /// }
541     /// ```
542     #[stable(feature = "rust1", since = "1.0.0")]
543     pub fn notify_all(&self) {
544         self.inner.notify_all()
545     }
546 }
547
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()
552     }
553 }
554
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 {
559         Condvar::new()
560     }
561 }