]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/condvar.rs
fix spacing issue in trpl/documentation doc
[rust.git] / src / libstd / sync / condvar.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use prelude::v1::*;
12
13 use sync::atomic::{AtomicUsize, Ordering};
14 use sync::{mutex, MutexGuard, PoisonError};
15 use sys_common::condvar as sys;
16 use sys_common::mutex as sys_mutex;
17 use sys_common::poison::{self, LockResult};
18 use sys::time::SteadyTime;
19 use time::Duration;
20
21 /// A Condition Variable
22 ///
23 /// Condition variables represent the ability to block a thread such that it
24 /// consumes no CPU time while waiting for an event to occur. Condition
25 /// variables are typically associated with a boolean predicate (a condition)
26 /// and a mutex. The predicate is always verified inside of the mutex before
27 /// determining that thread must block.
28 ///
29 /// Functions in this module will block the current **thread** of execution and
30 /// are bindings to system-provided condition variables where possible. Note
31 /// that this module places one additional restriction over the system condition
32 /// variables: each condvar can be used with precisely one mutex at runtime. Any
33 /// attempt to use multiple mutexes on the same condition variable will result
34 /// in a runtime panic. If this is not desired, then the unsafe primitives in
35 /// `sys` do not have this restriction but may result in undefined behavior.
36 ///
37 /// # Examples
38 ///
39 /// ```
40 /// use std::sync::{Arc, Mutex, Condvar};
41 /// use std::thread;
42 ///
43 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
44 /// let pair2 = pair.clone();
45 ///
46 /// // Inside of our lock, spawn a new thread, and then wait for it to start
47 /// thread::spawn(move|| {
48 ///     let &(ref lock, ref cvar) = &*pair2;
49 ///     let mut started = lock.lock().unwrap();
50 ///     *started = true;
51 ///     cvar.notify_one();
52 /// });
53 ///
54 /// // wait for the thread to start up
55 /// let &(ref lock, ref cvar) = &*pair;
56 /// let mut started = lock.lock().unwrap();
57 /// while !*started {
58 ///     started = cvar.wait(started).unwrap();
59 /// }
60 /// ```
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub struct Condvar { inner: Box<StaticCondvar> }
63
64 /// Statically allocated condition variables.
65 ///
66 /// This structure is identical to `Condvar` except that it is suitable for use
67 /// in static initializers for other structures.
68 ///
69 /// # Examples
70 ///
71 /// ```
72 /// #![feature(static_condvar)]
73 ///
74 /// use std::sync::{StaticCondvar, CONDVAR_INIT};
75 ///
76 /// static CVAR: StaticCondvar = CONDVAR_INIT;
77 /// ```
78 #[unstable(feature = "static_condvar",
79            reason = "may be merged with Condvar in the future",
80            issue = "27717")]
81 pub struct StaticCondvar {
82     inner: sys::Condvar,
83     mutex: AtomicUsize,
84 }
85
86 /// Constant initializer for a statically allocated condition variable.
87 #[unstable(feature = "static_condvar",
88            reason = "may be merged with Condvar in the future",
89            issue = "27717")]
90 pub const CONDVAR_INIT: StaticCondvar = StaticCondvar::new();
91
92 impl Condvar {
93     /// Creates a new condition variable which is ready to be waited on and
94     /// notified.
95     #[stable(feature = "rust1", since = "1.0.0")]
96     pub fn new() -> Condvar {
97         Condvar {
98             inner: box StaticCondvar {
99                 inner: sys::Condvar::new(),
100                 mutex: AtomicUsize::new(0),
101             }
102         }
103     }
104
105     /// Blocks the current thread until this condition variable receives a
106     /// notification.
107     ///
108     /// This function will atomically unlock the mutex specified (represented by
109     /// `mutex_guard`) and block the current thread. This means that any calls
110     /// to `notify_*()` which happen logically after the mutex is unlocked are
111     /// candidates to wake this thread up. When this function call returns, the
112     /// lock specified will have been re-acquired.
113     ///
114     /// Note that this function is susceptible to spurious wakeups. Condition
115     /// variables normally have a boolean predicate associated with them, and
116     /// the predicate must always be checked each time this function returns to
117     /// protect against spurious wakeups.
118     ///
119     /// # Failure
120     ///
121     /// This function will return an error if the mutex being waited on is
122     /// poisoned when this thread re-acquires the lock. For more information,
123     /// see information about poisoning on the Mutex type.
124     ///
125     /// # Panics
126     ///
127     /// This function will `panic!()` if it is used with more than one mutex
128     /// over time. Each condition variable is dynamically bound to exactly one
129     /// mutex to ensure defined behavior across platforms. If this functionality
130     /// is not desired, then unsafe primitives in `sys` are provided.
131     #[stable(feature = "rust1", since = "1.0.0")]
132     pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
133                        -> LockResult<MutexGuard<'a, T>> {
134         unsafe {
135             let me: &'static Condvar = &*(self as *const _);
136             me.inner.wait(guard)
137         }
138     }
139
140     /// Waits on this condition variable for a notification, timing out after a
141     /// specified duration.
142     ///
143     /// The semantics of this function are equivalent to `wait()`
144     /// except that the thread will be blocked for roughly no longer
145     /// than `ms` milliseconds. This method should not be used for
146     /// precise timing due to anomalies such as preemption or platform
147     /// differences that may not cause the maximum amount of time
148     /// waited to be precisely `ms`.
149     ///
150     /// The returned boolean is `false` only if the timeout is known
151     /// to have elapsed.
152     ///
153     /// Like `wait`, the lock specified will be re-acquired when this function
154     /// returns, regardless of whether the timeout elapsed or not.
155     #[stable(feature = "rust1", since = "1.0.0")]
156     pub fn wait_timeout_ms<'a, T>(&self, guard: MutexGuard<'a, T>, ms: u32)
157                                   -> LockResult<(MutexGuard<'a, T>, bool)> {
158         unsafe {
159             let me: &'static Condvar = &*(self as *const _);
160             me.inner.wait_timeout_ms(guard, ms)
161         }
162     }
163
164     /// Waits on this condition variable for a notification, timing out after a
165     /// specified duration.
166     ///
167     /// The semantics of this function are equivalent to `wait()` except that
168     /// the thread will be blocked for roughly no longer than `dur`. This
169     /// method should not be used for precise timing due to anomalies such as
170     /// preemption or platform differences that may not cause the maximum
171     /// amount of time waited to be precisely `dur`.
172     ///
173     /// The returned boolean is `false` only if the timeout is known
174     /// to have elapsed.
175     ///
176     /// Like `wait`, the lock specified will be re-acquired when this function
177     /// returns, regardless of whether the timeout elapsed or not.
178     #[unstable(feature = "wait_timeout", reason = "waiting for Duration",
179                issue = "27772")]
180     pub fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>,
181                                dur: Duration)
182                                -> LockResult<(MutexGuard<'a, T>, bool)> {
183         unsafe {
184             let me: &'static Condvar = &*(self as *const _);
185             me.inner.wait_timeout(guard, dur)
186         }
187     }
188
189     /// Waits on this condition variable for a notification, timing out after a
190     /// specified duration.
191     ///
192     /// The semantics of this function are equivalent to `wait_timeout` except
193     /// that the implementation will repeatedly wait while the duration has not
194     /// passed and the provided function returns `false`.
195     #[unstable(feature = "wait_timeout_with",
196                reason = "unsure if this API is broadly needed or what form it should take",
197                issue = "27748")]
198     pub fn wait_timeout_with<'a, T, F>(&self,
199                                        guard: MutexGuard<'a, T>,
200                                        dur: Duration,
201                                        f: F)
202                                        -> LockResult<(MutexGuard<'a, T>, bool)>
203             where F: FnMut(LockResult<&mut T>) -> bool {
204         unsafe {
205             let me: &'static Condvar = &*(self as *const _);
206             me.inner.wait_timeout_with(guard, dur, f)
207         }
208     }
209
210     /// Wakes up one blocked thread on this condvar.
211     ///
212     /// If there is a blocked thread on this condition variable, then it will
213     /// be woken up from its call to `wait` or `wait_timeout`. Calls to
214     /// `notify_one` are not buffered in any way.
215     ///
216     /// To wake up all threads, see `notify_all()`.
217     #[stable(feature = "rust1", since = "1.0.0")]
218     pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } }
219
220     /// Wakes up all blocked threads on this condvar.
221     ///
222     /// This method will ensure that any current waiters on the condition
223     /// variable are awoken. Calls to `notify_all()` are not buffered in any
224     /// way.
225     ///
226     /// To wake up only one thread, see `notify_one()`.
227     #[stable(feature = "rust1", since = "1.0.0")]
228     pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } }
229 }
230
231 #[stable(feature = "rust1", since = "1.0.0")]
232 impl Drop for Condvar {
233     fn drop(&mut self) {
234         unsafe { self.inner.inner.destroy() }
235     }
236 }
237
238 impl StaticCondvar {
239     /// Creates a new condition variable
240     #[unstable(feature = "static_condvar",
241                reason = "may be merged with Condvar in the future",
242                issue = "27717")]
243     pub const fn new() -> StaticCondvar {
244         StaticCondvar {
245             inner: sys::Condvar::new(),
246             mutex: AtomicUsize::new(0),
247         }
248     }
249
250     /// Blocks the current thread until this condition variable receives a
251     /// notification.
252     ///
253     /// See `Condvar::wait`.
254     #[unstable(feature = "static_condvar",
255                reason = "may be merged with Condvar in the future",
256                issue = "27717")]
257     pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
258                        -> LockResult<MutexGuard<'a, T>> {
259         let poisoned = unsafe {
260             let lock = mutex::guard_lock(&guard);
261             self.verify(lock);
262             self.inner.wait(lock);
263             mutex::guard_poison(&guard).get()
264         };
265         if poisoned {
266             Err(PoisonError::new(guard))
267         } else {
268             Ok(guard)
269         }
270     }
271
272     /// Waits on this condition variable for a notification, timing out after a
273     /// specified duration.
274     ///
275     /// See `Condvar::wait_timeout`.
276     #[unstable(feature = "static_condvar",
277                reason = "may be merged with Condvar in the future",
278                issue = "27717")]
279     pub fn wait_timeout_ms<'a, T>(&'static self, guard: MutexGuard<'a, T>, ms: u32)
280                                   -> LockResult<(MutexGuard<'a, T>, bool)> {
281         self.wait_timeout(guard, Duration::from_millis(ms as u64))
282     }
283
284     /// Waits on this condition variable for a notification, timing out after a
285     /// specified duration.
286     ///
287     /// See `Condvar::wait_timeout`.
288     #[unstable(feature = "static_condvar",
289                reason = "may be merged with Condvar in the future",
290                issue = "27717")]
291     pub fn wait_timeout<'a, T>(&'static self,
292                                guard: MutexGuard<'a, T>,
293                                timeout: Duration)
294                                -> LockResult<(MutexGuard<'a, T>, bool)> {
295         let (poisoned, success) = unsafe {
296             let lock = mutex::guard_lock(&guard);
297             self.verify(lock);
298             let success = self.inner.wait_timeout(lock, timeout);
299             (mutex::guard_poison(&guard).get(), success)
300         };
301         if poisoned {
302             Err(PoisonError::new((guard, success)))
303         } else {
304             Ok((guard, success))
305         }
306     }
307
308     /// Waits on this condition variable for a notification, timing out after a
309     /// specified duration.
310     ///
311     /// The implementation will repeatedly wait while the duration has not
312     /// passed and the function returns `false`.
313     ///
314     /// See `Condvar::wait_timeout_with`.
315     #[unstable(feature = "static_condvar",
316                reason = "may be merged with Condvar in the future",
317                issue = "27717")]
318     pub fn wait_timeout_with<'a, T, F>(&'static self,
319                                        guard: MutexGuard<'a, T>,
320                                        dur: Duration,
321                                        mut f: F)
322                                        -> LockResult<(MutexGuard<'a, T>, bool)>
323             where F: FnMut(LockResult<&mut T>) -> bool {
324         // This could be made more efficient by pushing the implementation into
325         // sys::condvar
326         let start = SteadyTime::now();
327         let mut guard_result: LockResult<MutexGuard<'a, T>> = Ok(guard);
328         while !f(guard_result
329                     .as_mut()
330                     .map(|g| &mut **g)
331                     .map_err(|e| PoisonError::new(&mut **e.get_mut()))) {
332             let now = SteadyTime::now();
333             let consumed = &now - &start;
334             let guard = guard_result.unwrap_or_else(|e| e.into_inner());
335             let (new_guard_result, no_timeout) = if consumed > dur {
336                 (Ok(guard), false)
337             } else {
338                 match self.wait_timeout(guard, dur - consumed) {
339                     Ok((new_guard, no_timeout)) => (Ok(new_guard), no_timeout),
340                     Err(err) => {
341                         let (new_guard, no_timeout) = err.into_inner();
342                         (Err(PoisonError::new(new_guard)), no_timeout)
343                     }
344                 }
345             };
346             guard_result = new_guard_result;
347             if !no_timeout {
348                 let result = f(guard_result
349                                     .as_mut()
350                                     .map(|g| &mut **g)
351                                     .map_err(|e| PoisonError::new(&mut **e.get_mut())));
352                 return poison::map_result(guard_result, |g| (g, result));
353             }
354         }
355
356         poison::map_result(guard_result, |g| (g, true))
357     }
358
359     /// Wakes up one blocked thread on this condvar.
360     ///
361     /// See `Condvar::notify_one`.
362     #[unstable(feature = "static_condvar",
363                reason = "may be merged with Condvar in the future",
364                issue = "27717")]
365     pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
366
367     /// Wakes up all blocked threads on this condvar.
368     ///
369     /// See `Condvar::notify_all`.
370     #[unstable(feature = "static_condvar",
371                reason = "may be merged with Condvar in the future",
372                issue = "27717")]
373     pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
374
375     /// Deallocates all resources associated with this static condvar.
376     ///
377     /// This method is unsafe to call as there is no guarantee that there are no
378     /// active users of the condvar, and this also doesn't prevent any future
379     /// users of the condvar. This method is required to be called to not leak
380     /// memory on all platforms.
381     #[unstable(feature = "static_condvar",
382                reason = "may be merged with Condvar in the future",
383                issue = "27717")]
384     pub unsafe fn destroy(&'static self) {
385         self.inner.destroy()
386     }
387
388     fn verify(&self, mutex: &sys_mutex::Mutex) {
389         let addr = mutex as *const _ as usize;
390         match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
391             // If we got out 0, then we have successfully bound the mutex to
392             // this cvar.
393             0 => {}
394
395             // If we get out a value that's the same as `addr`, then someone
396             // already beat us to the punch.
397             n if n == addr => {}
398
399             // Anything else and we're using more than one mutex on this cvar,
400             // which is currently disallowed.
401             _ => panic!("attempted to use a condition variable with two \
402                          mutexes"),
403         }
404     }
405 }
406
407 #[cfg(test)]
408 mod tests {
409     use prelude::v1::*;
410
411     use super::StaticCondvar;
412     use sync::mpsc::channel;
413     use sync::{StaticMutex, Condvar, Mutex, Arc};
414     use sync::atomic::{AtomicUsize, Ordering};
415     use thread;
416     use time::Duration;
417     use u32;
418
419     #[test]
420     fn smoke() {
421         let c = Condvar::new();
422         c.notify_one();
423         c.notify_all();
424     }
425
426     #[test]
427     fn static_smoke() {
428         static C: StaticCondvar = StaticCondvar::new();
429         C.notify_one();
430         C.notify_all();
431         unsafe { C.destroy(); }
432     }
433
434     #[test]
435     fn notify_one() {
436         static C: StaticCondvar = StaticCondvar::new();
437         static M: StaticMutex = StaticMutex::new();
438
439         let g = M.lock().unwrap();
440         let _t = thread::spawn(move|| {
441             let _g = M.lock().unwrap();
442             C.notify_one();
443         });
444         let g = C.wait(g).unwrap();
445         drop(g);
446         unsafe { C.destroy(); M.destroy(); }
447     }
448
449     #[test]
450     fn notify_all() {
451         const N: usize = 10;
452
453         let data = Arc::new((Mutex::new(0), Condvar::new()));
454         let (tx, rx) = channel();
455         for _ in 0..N {
456             let data = data.clone();
457             let tx = tx.clone();
458             thread::spawn(move|| {
459                 let &(ref lock, ref cond) = &*data;
460                 let mut cnt = lock.lock().unwrap();
461                 *cnt += 1;
462                 if *cnt == N {
463                     tx.send(()).unwrap();
464                 }
465                 while *cnt != 0 {
466                     cnt = cond.wait(cnt).unwrap();
467                 }
468                 tx.send(()).unwrap();
469             });
470         }
471         drop(tx);
472
473         let &(ref lock, ref cond) = &*data;
474         rx.recv().unwrap();
475         let mut cnt = lock.lock().unwrap();
476         *cnt = 0;
477         cond.notify_all();
478         drop(cnt);
479
480         for _ in 0..N {
481             rx.recv().unwrap();
482         }
483     }
484
485     #[test]
486     fn wait_timeout_ms() {
487         static C: StaticCondvar = StaticCondvar::new();
488         static M: StaticMutex = StaticMutex::new();
489
490         let g = M.lock().unwrap();
491         let (g, _no_timeout) = C.wait_timeout_ms(g, 1).unwrap();
492         // spurious wakeups mean this isn't necessarily true
493         // assert!(!no_timeout);
494         let _t = thread::spawn(move || {
495             let _g = M.lock().unwrap();
496             C.notify_one();
497         });
498         let (g, no_timeout) = C.wait_timeout_ms(g, u32::MAX).unwrap();
499         assert!(no_timeout);
500         drop(g);
501         unsafe { C.destroy(); M.destroy(); }
502     }
503
504     #[test]
505     fn wait_timeout_with() {
506         static C: StaticCondvar = StaticCondvar::new();
507         static M: StaticMutex = StaticMutex::new();
508         static S: AtomicUsize = AtomicUsize::new(0);
509
510         let g = M.lock().unwrap();
511         let (g, success) = C.wait_timeout_with(g, Duration::new(0, 1000), |_| {
512             false
513         }).unwrap();
514         assert!(!success);
515
516         let (tx, rx) = channel();
517         let _t = thread::spawn(move || {
518             rx.recv().unwrap();
519             let g = M.lock().unwrap();
520             S.store(1, Ordering::SeqCst);
521             C.notify_one();
522             drop(g);
523
524             rx.recv().unwrap();
525             let g = M.lock().unwrap();
526             S.store(2, Ordering::SeqCst);
527             C.notify_one();
528             drop(g);
529
530             rx.recv().unwrap();
531             let _g = M.lock().unwrap();
532             S.store(3, Ordering::SeqCst);
533             C.notify_one();
534         });
535
536         let mut state = 0;
537         let day = 24 * 60 * 60;
538         let (_g, success) = C.wait_timeout_with(g, Duration::new(day, 0), |_| {
539             assert_eq!(state, S.load(Ordering::SeqCst));
540             tx.send(()).unwrap();
541             state += 1;
542             match state {
543                 1|2 => false,
544                 _ => true,
545             }
546         }).unwrap();
547         assert!(success);
548     }
549
550     #[test]
551     #[should_panic]
552     fn two_mutexes() {
553         static M1: StaticMutex = StaticMutex::new();
554         static M2: StaticMutex = StaticMutex::new();
555         static C: StaticCondvar = StaticCondvar::new();
556
557         let mut g = M1.lock().unwrap();
558         let _t = thread::spawn(move|| {
559             let _g = M1.lock().unwrap();
560             C.notify_one();
561         });
562         g = C.wait(g).unwrap();
563         drop(g);
564
565         let _ = C.wait(M2.lock().unwrap()).unwrap();
566     }
567 }