]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/condvar.rs
auto merge of #21132 : sfackler/rust/wait_timeout, r=alexcrichton
[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, ATOMIC_USIZE_INIT};
14 use sync::poison::{self, LockResult};
15 use sys::time::SteadyTime;
16 use sys_common::condvar as sys;
17 use sys_common::mutex as sys_mutex;
18 use time::Duration;
19 use sync::{mutex, MutexGuard};
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 /// # Example
38 ///
39 /// ```
40 /// use std::sync::{Arc, Mutex, Condvar};
41 /// use std::thread::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]
62 pub struct Condvar { inner: Box<StaticCondvar> }
63
64 unsafe impl Send for Condvar {}
65 unsafe impl Sync for Condvar {}
66
67 /// Statically allocated condition variables.
68 ///
69 /// This structure is identical to `Condvar` except that it is suitable for use
70 /// in static initializers for other structures.
71 ///
72 /// # Example
73 ///
74 /// ```
75 /// use std::sync::{StaticCondvar, CONDVAR_INIT};
76 ///
77 /// static CVAR: StaticCondvar = CONDVAR_INIT;
78 /// ```
79 #[unstable = "may be merged with Condvar in the future"]
80 pub struct StaticCondvar {
81     inner: sys::Condvar,
82     mutex: AtomicUsize,
83 }
84
85 unsafe impl Send for StaticCondvar {}
86 unsafe impl Sync for StaticCondvar {}
87
88 /// Constant initializer for a statically allocated condition variable.
89 #[unstable = "may be merged with Condvar in the future"]
90 pub const CONDVAR_INIT: StaticCondvar = StaticCondvar {
91     inner: sys::CONDVAR_INIT,
92     mutex: ATOMIC_USIZE_INIT,
93 };
94
95 impl Condvar {
96     /// Creates a new condition variable which is ready to be waited on and
97     /// notified.
98     #[stable]
99     pub fn new() -> Condvar {
100         Condvar {
101             inner: box StaticCondvar {
102                 inner: unsafe { sys::Condvar::new() },
103                 mutex: AtomicUsize::new(0),
104             }
105         }
106     }
107
108     /// Block the current thread until this condition variable receives a
109     /// notification.
110     ///
111     /// This function will atomically unlock the mutex specified (represented by
112     /// `mutex_guard`) and block the current thread. This means that any calls
113     /// to `notify_*()` which happen logically after the mutex is unlocked are
114     /// candidates to wake this thread up. When this function call returns, the
115     /// lock specified will have been re-acquired.
116     ///
117     /// Note that this function is susceptible to spurious wakeups. Condition
118     /// variables normally have a boolean predicate associated with them, and
119     /// the predicate must always be checked each time this function returns to
120     /// protect against spurious wakeups.
121     ///
122     /// # Failure
123     ///
124     /// This function will return an error if the mutex being waited on is
125     /// poisoned when this thread re-acquires the lock. For more information,
126     /// see information about poisoning on the Mutex type.
127     ///
128     /// # Panics
129     ///
130     /// This function will `panic!()` if it is used with more than one mutex
131     /// over time. Each condition variable is dynamically bound to exactly one
132     /// mutex to ensure defined behavior across platforms. If this functionality
133     /// is not desired, then unsafe primitives in `sys` are provided.
134     #[stable]
135     pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
136                        -> LockResult<MutexGuard<'a, T>> {
137         unsafe {
138             let me: &'static Condvar = &*(self as *const _);
139             me.inner.wait(guard)
140         }
141     }
142
143     /// Wait on this condition variable for a notification, timing out after a
144     /// specified duration.
145     ///
146     /// The semantics of this function are equivalent to `wait()` except that
147     /// the thread will be blocked for roughly no longer than `dur`. This method
148     /// should not be used for precise timing due to anomalies such as
149     /// preemption or platform differences that may not cause the maximum amount
150     /// of time waited to be precisely `dur`.
151     ///
152     /// If the wait timed out, then `false` will be returned. Otherwise if a
153     /// notification was received then `true` will be returned.
154     ///
155     /// Like `wait`, the lock specified will be re-acquired when this function
156     /// returns, regardless of whether the timeout elapsed or not.
157     #[unstable]
158     pub fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>, dur: Duration)
159                            -> LockResult<(MutexGuard<'a, T>, bool)> {
160         unsafe {
161             let me: &'static Condvar = &*(self as *const _);
162             me.inner.wait_timeout(guard, dur)
163         }
164     }
165
166     /// Wait on this condition variable for a notification, timing out after a
167     /// specified duration.
168     ///
169     /// The semantics of this function are equivalent to `wait_timeout` except
170     /// that the implementation will repeatedly wait while the duration has not
171     /// passed and the provided function returns `false`.
172     #[unstable]
173     pub fn wait_timeout_with<'a, T, F>(&self,
174                                        guard: MutexGuard<'a, T>,
175                                        dur: Duration,
176                                        f: F)
177                                        -> LockResult<(MutexGuard<'a, T>, bool)>
178             where F: FnMut(LockResult<&mut T>) -> bool {
179         unsafe {
180             let me: &'static Condvar = &*(self as *const _);
181             me.inner.wait_timeout_with(guard, dur, f)
182         }
183     }
184
185     /// Wake up one blocked thread on this condvar.
186     ///
187     /// If there is a blocked thread on this condition variable, then it will
188     /// be woken up from its call to `wait` or `wait_timeout`. Calls to
189     /// `notify_one` are not buffered in any way.
190     ///
191     /// To wake up all threads, see `notify_all()`.
192     #[stable]
193     pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } }
194
195     /// Wake up all blocked threads on this condvar.
196     ///
197     /// This method will ensure that any current waiters on the condition
198     /// variable are awoken. Calls to `notify_all()` are not buffered in any
199     /// way.
200     ///
201     /// To wake up only one thread, see `notify_one()`.
202     #[stable]
203     pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } }
204 }
205
206 #[stable]
207 impl Drop for Condvar {
208     fn drop(&mut self) {
209         unsafe { self.inner.inner.destroy() }
210     }
211 }
212
213 impl StaticCondvar {
214     /// Block the current thread until this condition variable receives a
215     /// notification.
216     ///
217     /// See `Condvar::wait`.
218     #[unstable = "may be merged with Condvar in the future"]
219     pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
220                        -> LockResult<MutexGuard<'a, T>> {
221         let poisoned = unsafe {
222             let lock = mutex::guard_lock(&guard);
223             self.verify(lock);
224             self.inner.wait(lock);
225             mutex::guard_poison(&guard).get()
226         };
227         if poisoned {
228             Err(poison::new_poison_error(guard))
229         } else {
230             Ok(guard)
231         }
232     }
233
234     /// Wait on this condition variable for a notification, timing out after a
235     /// specified duration.
236     ///
237     /// See `Condvar::wait_timeout`.
238     #[unstable = "may be merged with Condvar in the future"]
239     pub fn wait_timeout<'a, T>(&'static self, guard: MutexGuard<'a, T>, dur: Duration)
240                                -> LockResult<(MutexGuard<'a, T>, bool)> {
241         let (poisoned, success) = unsafe {
242             let lock = mutex::guard_lock(&guard);
243             self.verify(lock);
244             let success = self.inner.wait_timeout(lock, dur);
245             (mutex::guard_poison(&guard).get(), success)
246         };
247         if poisoned {
248             Err(poison::new_poison_error((guard, success)))
249         } else {
250             Ok((guard, success))
251         }
252     }
253
254     /// Wait on this condition variable for a notification, timing out after a
255     /// specified duration.
256     ///
257     /// The implementation will repeatedly wait while the duration has not
258     /// passed and the function returns `false`.
259     ///
260     /// See `Condvar::wait_timeout_with`.
261     #[unstable = "may be merged with Condvar in the future"]
262     pub fn wait_timeout_with<'a, T, F>(&'static self,
263                                        guard: MutexGuard<'a, T>,
264                                        dur: Duration,
265                                        mut f: F)
266                                        -> LockResult<(MutexGuard<'a, T>, bool)>
267             where F: FnMut(LockResult<&mut T>) -> bool {
268         // This could be made more efficient by pushing the implementation into sys::condvar
269         let start = SteadyTime::now();
270         let mut guard_result: LockResult<MutexGuard<'a, T>> = Ok(guard);
271         while !f(guard_result
272                     .as_mut()
273                     .map(|g| &mut **g)
274                     .map_err(|e| poison::new_poison_error(&mut **e.get_mut()))) {
275             let now = SteadyTime::now();
276             let consumed = &now - &start;
277             let guard = guard_result.unwrap_or_else(|e| e.into_inner());
278             let (new_guard_result, no_timeout) = match self.wait_timeout(guard, dur - consumed) {
279                 Ok((new_guard, no_timeout)) => (Ok(new_guard), no_timeout),
280                 Err(err) => {
281                     let (new_guard, no_timeout) = err.into_inner();
282                     (Err(poison::new_poison_error(new_guard)), no_timeout)
283                 }
284             };
285             guard_result = new_guard_result;
286             if !no_timeout {
287                 let result = f(guard_result
288                                     .as_mut()
289                                     .map(|g| &mut **g)
290                                     .map_err(|e| poison::new_poison_error(&mut **e.get_mut())));
291                 return poison::map_result(guard_result, |g| (g, result));
292             }
293         }
294
295         poison::map_result(guard_result, |g| (g, true))
296     }
297
298     /// Wake up one blocked thread on this condvar.
299     ///
300     /// See `Condvar::notify_one`.
301     #[unstable = "may be merged with Condvar in the future"]
302     pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
303
304     /// Wake up all blocked threads on this condvar.
305     ///
306     /// See `Condvar::notify_all`.
307     #[unstable = "may be merged with Condvar in the future"]
308     pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
309
310     /// Deallocate all resources associated with this static condvar.
311     ///
312     /// This method is unsafe to call as there is no guarantee that there are no
313     /// active users of the condvar, and this also doesn't prevent any future
314     /// users of the condvar. This method is required to be called to not leak
315     /// memory on all platforms.
316     #[unstable = "may be merged with Condvar in the future"]
317     pub unsafe fn destroy(&'static self) {
318         self.inner.destroy()
319     }
320
321     fn verify(&self, mutex: &sys_mutex::Mutex) {
322         let addr = mutex as *const _ as uint;
323         match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
324             // If we got out 0, then we have successfully bound the mutex to
325             // this cvar.
326             0 => {}
327
328             // If we get out a value that's the same as `addr`, then someone
329             // already beat us to the punch.
330             n if n == addr => {}
331
332             // Anything else and we're using more than one mutex on this cvar,
333             // which is currently disallowed.
334             _ => panic!("attempted to use a condition variable with two \
335                          mutexes"),
336         }
337     }
338 }
339
340 #[cfg(test)]
341 mod tests {
342     use prelude::v1::*;
343
344     use super::{StaticCondvar, CONDVAR_INIT};
345     use sync::mpsc::channel;
346     use sync::{StaticMutex, MUTEX_INIT, Condvar, Mutex, Arc};
347     use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
348     use thread::Thread;
349     use time::Duration;
350
351     #[test]
352     fn smoke() {
353         let c = Condvar::new();
354         c.notify_one();
355         c.notify_all();
356     }
357
358     #[test]
359     fn static_smoke() {
360         static C: StaticCondvar = CONDVAR_INIT;
361         C.notify_one();
362         C.notify_all();
363         unsafe { C.destroy(); }
364     }
365
366     #[test]
367     fn notify_one() {
368         static C: StaticCondvar = CONDVAR_INIT;
369         static M: StaticMutex = MUTEX_INIT;
370
371         let g = M.lock().unwrap();
372         let _t = Thread::spawn(move|| {
373             let _g = M.lock().unwrap();
374             C.notify_one();
375         });
376         let g = C.wait(g).unwrap();
377         drop(g);
378         unsafe { C.destroy(); M.destroy(); }
379     }
380
381     #[test]
382     fn notify_all() {
383         const N: uint = 10;
384
385         let data = Arc::new((Mutex::new(0), Condvar::new()));
386         let (tx, rx) = channel();
387         for _ in range(0, N) {
388             let data = data.clone();
389             let tx = tx.clone();
390             Thread::spawn(move|| {
391                 let &(ref lock, ref cond) = &*data;
392                 let mut cnt = lock.lock().unwrap();
393                 *cnt += 1;
394                 if *cnt == N {
395                     tx.send(()).unwrap();
396                 }
397                 while *cnt != 0 {
398                     cnt = cond.wait(cnt).unwrap();
399                 }
400                 tx.send(()).unwrap();
401             });
402         }
403         drop(tx);
404
405         let &(ref lock, ref cond) = &*data;
406         rx.recv().unwrap();
407         let mut cnt = lock.lock().unwrap();
408         *cnt = 0;
409         cond.notify_all();
410         drop(cnt);
411
412         for _ in range(0, N) {
413             rx.recv().unwrap();
414         }
415     }
416
417     #[test]
418     fn wait_timeout() {
419         static C: StaticCondvar = CONDVAR_INIT;
420         static M: StaticMutex = MUTEX_INIT;
421
422         let g = M.lock().unwrap();
423         let (g, success) = C.wait_timeout(g, Duration::nanoseconds(1000)).unwrap();
424         assert!(!success);
425         let _t = Thread::spawn(move || {
426             let _g = M.lock().unwrap();
427             C.notify_one();
428         });
429         let (g, success) = C.wait_timeout(g, Duration::days(1)).unwrap();
430         assert!(success);
431         drop(g);
432         unsafe { C.destroy(); M.destroy(); }
433     }
434
435     #[test]
436     fn wait_timeout_with() {
437         static C: StaticCondvar = CONDVAR_INIT;
438         static M: StaticMutex = MUTEX_INIT;
439         static S: AtomicUsize = ATOMIC_USIZE_INIT;
440
441         let g = M.lock().unwrap();
442         let (g, success) = C.wait_timeout_with(g, Duration::nanoseconds(1000), |_| false).unwrap();
443         assert!(!success);
444
445         let (tx, rx) = channel();
446         let _t = Thread::scoped(move || {
447             rx.recv().unwrap();
448             let g = M.lock().unwrap();
449             S.store(1, Ordering::SeqCst);
450             C.notify_one();
451             drop(g);
452
453             rx.recv().unwrap();
454             let g = M.lock().unwrap();
455             S.store(2, Ordering::SeqCst);
456             C.notify_one();
457             drop(g);
458
459             rx.recv().unwrap();
460             let _g = M.lock().unwrap();
461             S.store(3, Ordering::SeqCst);
462             C.notify_one();
463         });
464
465         let mut state = 0;
466         let (_g, success) = C.wait_timeout_with(g, Duration::days(1), |_| {
467             assert_eq!(state, S.load(Ordering::SeqCst));
468             tx.send(()).unwrap();
469             state += 1;
470             match state {
471                 1|2 => false,
472                 _ => true,
473             }
474         }).unwrap();
475         assert!(success);
476     }
477
478     #[test]
479     #[should_fail]
480     fn two_mutexes() {
481         static M1: StaticMutex = MUTEX_INIT;
482         static M2: StaticMutex = MUTEX_INIT;
483         static C: StaticCondvar = CONDVAR_INIT;
484
485         let mut g = M1.lock().unwrap();
486         let _t = Thread::spawn(move|| {
487             let _g = M1.lock().unwrap();
488             C.notify_one();
489         });
490         g = C.wait(g).unwrap();
491         drop(g);
492
493         let _ = C.wait(M2.lock().unwrap()).unwrap();
494     }
495 }