]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/condvar.rs
Auto merge of #85020 - lrh2000:named-upvars, r=tmandry
[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     pub fn new() -> Condvar {
125         Condvar { inner: sys::Condvar::new() }
126     }
127
128     /// Blocks the current thread until this condition variable receives a
129     /// notification.
130     ///
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.
136     ///
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.
141     ///
142     /// # Errors
143     ///
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.
147     ///
148     /// # Panics
149     ///
150     /// This function may [`panic!`] if it is used with more than one mutex
151     /// over time.
152     ///
153     /// [`notify_one`]: Self::notify_one
154     /// [`notify_all`]: Self::notify_all
155     /// [poisoning]: super::Mutex#poisoning
156     /// [`Mutex`]: super::Mutex
157     ///
158     /// # Examples
159     ///
160     /// ```
161     /// use std::sync::{Arc, Mutex, Condvar};
162     /// use std::thread;
163     ///
164     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
165     /// let pair2 = Arc::clone(&pair);
166     ///
167     /// thread::spawn(move|| {
168     ///     let (lock, cvar) = &*pair2;
169     ///     let mut started = lock.lock().unwrap();
170     ///     *started = true;
171     ///     // We notify the condvar that the value has changed.
172     ///     cvar.notify_one();
173     /// });
174     ///
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();
181     /// }
182     /// ```
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()
189         };
190         if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
191     }
192
193     /// Blocks the current thread until this condition variable receives a
194     /// notification and the provided condition is false.
195     ///
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.
201     ///
202     /// # Errors
203     ///
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.
207     ///
208     /// [`notify_one`]: Self::notify_one
209     /// [`notify_all`]: Self::notify_all
210     /// [poisoning]: super::Mutex#poisoning
211     /// [`Mutex`]: super::Mutex
212     ///
213     /// # Examples
214     ///
215     /// ```
216     /// use std::sync::{Arc, Mutex, Condvar};
217     /// use std::thread;
218     ///
219     /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
220     /// let pair2 = Arc::clone(&pair);
221     ///
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();
228     /// });
229     ///
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();
234     /// ```
235     #[stable(feature = "wait_until", since = "1.42.0")]
236     pub fn wait_while<'a, T, F>(
237         &self,
238         mut guard: MutexGuard<'a, T>,
239         mut condition: F,
240     ) -> LockResult<MutexGuard<'a, T>>
241     where
242         F: FnMut(&mut T) -> bool,
243     {
244         while condition(&mut *guard) {
245             guard = self.wait(guard)?;
246         }
247         Ok(guard)
248     }
249
250     /// Waits on this condition variable for a notification, timing out after a
251     /// specified duration.
252     ///
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`.
259     ///
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
262     /// the system time.
263     ///
264     /// The returned boolean is `false` only if the timeout is known
265     /// to have elapsed.
266     ///
267     /// Like [`wait`], the lock specified will be re-acquired when this function
268     /// returns, regardless of whether the timeout elapsed or not.
269     ///
270     /// [`wait`]: Self::wait
271     ///
272     /// # Examples
273     ///
274     /// ```
275     /// use std::sync::{Arc, Mutex, Condvar};
276     /// use std::thread;
277     ///
278     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
279     /// let pair2 = Arc::clone(&pair);
280     ///
281     /// thread::spawn(move|| {
282     ///     let (lock, cvar) = &*pair2;
283     ///     let mut started = lock.lock().unwrap();
284     ///     *started = true;
285     ///     // We notify the condvar that the value has changed.
286     ///     cvar.notify_one();
287     /// });
288     ///
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.
293     /// loop {
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.
299     ///         break
300     ///     }
301     /// }
302     /// ```
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>(
306         &self,
307         guard: MutexGuard<'a, T>,
308         ms: u32,
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()))
312     }
313
314     /// Waits on this condition variable for a notification, timing out after a
315     /// specified duration.
316     ///
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`.
322     ///
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.
333     ///
334     /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
335     /// known to have elapsed.
336     ///
337     /// Like [`wait`], the lock specified will be re-acquired when this function
338     /// returns, regardless of whether the timeout elapsed or not.
339     ///
340     /// [`wait`]: Self::wait
341     /// [`wait_timeout_while`]: Self::wait_timeout_while
342     ///
343     /// # Examples
344     ///
345     /// ```
346     /// use std::sync::{Arc, Mutex, Condvar};
347     /// use std::thread;
348     /// use std::time::Duration;
349     ///
350     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
351     /// let pair2 = Arc::clone(&pair);
352     ///
353     /// thread::spawn(move|| {
354     ///     let (lock, cvar) = &*pair2;
355     ///     let mut started = lock.lock().unwrap();
356     ///     *started = true;
357     ///     // We notify the condvar that the value has changed.
358     ///     cvar.notify_one();
359     /// });
360     ///
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
365     /// loop {
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.
371     ///         break
372     ///     }
373     /// }
374     /// ```
375     #[stable(feature = "wait_timeout", since = "1.5.0")]
376     pub fn wait_timeout<'a, T>(
377         &self,
378         guard: MutexGuard<'a, T>,
379         dur: Duration,
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))
385         };
386         if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
387     }
388
389     /// Waits on this condition variable for a notification, timing out after a
390     /// specified duration.
391     ///
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`.
397     ///
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
400     /// the system time.
401     ///
402     /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
403     /// known to have elapsed without the condition being met.
404     ///
405     /// Like [`wait_while`], the lock specified will be re-acquired when this
406     /// function returns, regardless of whether the timeout elapsed or not.
407     ///
408     /// [`wait_while`]: Self::wait_while
409     /// [`wait_timeout`]: Self::wait_timeout
410     ///
411     /// # Examples
412     ///
413     /// ```
414     /// use std::sync::{Arc, Mutex, Condvar};
415     /// use std::thread;
416     /// use std::time::Duration;
417     ///
418     /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
419     /// let pair2 = Arc::clone(&pair);
420     ///
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();
427     /// });
428     ///
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,
435     /// ).unwrap();
436     /// if result.1.timed_out() {
437     ///     // timed-out without the condition ever evaluating to false.
438     /// }
439     /// // access the locked mutex via result.0
440     /// ```
441     #[stable(feature = "wait_timeout_until", since = "1.42.0")]
442     pub fn wait_timeout_while<'a, T, F>(
443         &self,
444         mut guard: MutexGuard<'a, T>,
445         dur: Duration,
446         mut condition: F,
447     ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
448     where
449         F: FnMut(&mut T) -> bool,
450     {
451         let start = Instant::now();
452         loop {
453             if !condition(&mut *guard) {
454                 return Ok((guard, WaitTimeoutResult(false)));
455             }
456             let timeout = match dur.checked_sub(start.elapsed()) {
457                 Some(timeout) => timeout,
458                 None => return Ok((guard, WaitTimeoutResult(true))),
459             };
460             guard = self.wait_timeout(guard, timeout)?.0;
461         }
462     }
463
464     /// Wakes up one blocked thread on this condvar.
465     ///
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.
469     ///
470     /// To wake up all threads, see [`notify_all`].
471     ///
472     /// [`wait`]: Self::wait
473     /// [`wait_timeout`]: Self::wait_timeout
474     /// [`notify_all`]: Self::notify_all
475     ///
476     /// # Examples
477     ///
478     /// ```
479     /// use std::sync::{Arc, Mutex, Condvar};
480     /// use std::thread;
481     ///
482     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
483     /// let pair2 = Arc::clone(&pair);
484     ///
485     /// thread::spawn(move|| {
486     ///     let (lock, cvar) = &*pair2;
487     ///     let mut started = lock.lock().unwrap();
488     ///     *started = true;
489     ///     // We notify the condvar that the value has changed.
490     ///     cvar.notify_one();
491     /// });
492     ///
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();
499     /// }
500     /// ```
501     #[stable(feature = "rust1", since = "1.0.0")]
502     pub fn notify_one(&self) {
503         self.inner.notify_one()
504     }
505
506     /// Wakes up all blocked threads on this condvar.
507     ///
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
510     /// way.
511     ///
512     /// To wake up only one thread, see [`notify_one`].
513     ///
514     /// [`notify_one`]: Self::notify_one
515     ///
516     /// # Examples
517     ///
518     /// ```
519     /// use std::sync::{Arc, Mutex, Condvar};
520     /// use std::thread;
521     ///
522     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
523     /// let pair2 = Arc::clone(&pair);
524     ///
525     /// thread::spawn(move|| {
526     ///     let (lock, cvar) = &*pair2;
527     ///     let mut started = lock.lock().unwrap();
528     ///     *started = true;
529     ///     // We notify the condvar that the value has changed.
530     ///     cvar.notify_all();
531     /// });
532     ///
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();
539     /// }
540     /// ```
541     #[stable(feature = "rust1", since = "1.0.0")]
542     pub fn notify_all(&self) {
543         self.inner.notify_all()
544     }
545 }
546
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()
551     }
552 }
553
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 {
558         Condvar::new()
559     }
560 }