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.
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.
13 use sys::mutex::{self, Mutex};
17 pub struct Condvar { inner: UnsafeCell<ffi::pthread_cond_t> }
19 pub const CONDVAR_INIT: Condvar = Condvar {
20 inner: UnsafeCell { value: ffi::PTHREAD_COND_INITIALIZER },
25 pub unsafe fn new() -> Condvar {
26 // Might be moved and address is changing it is better to avoid
27 // initialization of potentially opaque OS data before it landed
28 Condvar { inner: UnsafeCell::new(ffi::PTHREAD_COND_INITIALIZER) }
32 pub unsafe fn notify_one(&self) {
33 let r = ffi::pthread_cond_signal(self.inner.get());
34 debug_assert_eq!(r, 0);
38 pub unsafe fn notify_all(&self) {
39 let r = ffi::pthread_cond_broadcast(self.inner.get());
40 debug_assert_eq!(r, 0);
44 pub unsafe fn wait(&self, mutex: &Mutex) {
45 let r = ffi::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
46 debug_assert_eq!(r, 0);
49 pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
50 assert!(dur >= Duration::nanoseconds(0));
52 // First, figure out what time it currently is
53 let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
54 let r = ffi::gettimeofday(&mut tv, 0 as *mut _);
55 debug_assert_eq!(r, 0);
57 // Offset that time with the specified duration
58 let abs = Duration::seconds(tv.tv_sec as i64) +
59 Duration::microseconds(tv.tv_usec as i64) +
61 let ns = abs.num_nanoseconds().unwrap() as u64;
62 let timeout = libc::timespec {
63 tv_sec: (ns / 1000000000) as libc::time_t,
64 tv_nsec: (ns % 1000000000) as libc::c_long,
68 let r = ffi::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
71 debug_assert_eq!(r as int, libc::ETIMEDOUT as int);
79 #[cfg(not(target_os = "dragonfly"))]
80 pub unsafe fn destroy(&self) {
81 let r = ffi::pthread_cond_destroy(self.inner.get());
82 debug_assert_eq!(r, 0);
86 #[cfg(target_os = "dragonfly")]
87 pub unsafe fn destroy(&self) {
88 let r = ffi::pthread_cond_destroy(self.inner.get());
89 // On DragonFly pthread_cond_destroy() returns EINVAL if called on
90 // a condvar that was just initialized with
91 // ffi::PTHREAD_COND_INITIALIZER. Once it is used or
92 // pthread_cond_init() is called, this behaviour no longer occurs.
93 debug_assert!(r == 0 || r == libc::EINVAL);