1 // Copyright 2013-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.
11 //! A native mutex and condition variable type.
13 //! This module contains bindings to the platform's native mutex/condition
14 //! variable primitives. It provides two types: `StaticNativeMutex`, which can
15 //! be statically initialized via the `NATIVE_MUTEX_INIT` value, and a simple
16 //! wrapper `NativeMutex` that has a destructor to clean up after itself. These
17 //! objects serve as both mutexes and condition variables simultaneously.
19 //! The static lock is lazily initialized, but it can only be unsafely
20 //! destroyed. A statically initialized lock doesn't necessarily have a time at
21 //! which it can get deallocated. For this reason, there is no `Drop`
22 //! implementation of the static mutex, but rather the `destroy()` method must
23 //! be invoked manually if destruction of the mutex is desired.
25 //! The non-static `NativeMutex` type does have a destructor, but cannot be
26 //! statically initialized.
28 //! It is not recommended to use this type for idiomatic rust use. These types
29 //! are appropriate where no other options are available, but other rust
30 //! concurrency primitives should be used before them: the `sync` crate defines
31 //! `StaticMutex` and `Mutex` types.
36 //! use std::rt::mutex::{NativeMutex, StaticNativeMutex, NATIVE_MUTEX_INIT};
38 //! // Use a statically initialized mutex
39 //! static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
42 //! let _guard = LOCK.lock();
43 //! } // automatically unlocked here
45 //! // Use a normally initialized mutex
47 //! let mut lock = NativeMutex::new();
50 //! let _guard = lock.lock();
51 //! } // unlocked here
53 //! // sometimes the RAII guard isn't appropriate
54 //! lock.lock_noguard();
55 //! lock.unlock_noguard();
56 //! } // `lock` is deallocated here
59 #![allow(non_camel_case_types)]
63 /// A native mutex suitable for storing in statics (that is, it has
64 /// the `destroy` method rather than a destructor).
66 /// Prefer the `NativeMutex` type where possible, since that does not
67 /// require manual deallocation.
68 pub struct StaticNativeMutex {
72 /// A native mutex with a destructor for clean-up.
74 /// See `StaticNativeMutex` for a version that is suitable for storing in
76 pub struct NativeMutex {
77 inner: StaticNativeMutex
80 /// Automatically unlocks the mutex that it was created from on
83 /// Using this makes lock-based code resilient to unwinding/task
84 /// failure, because the lock will be automatically unlocked even
87 pub struct LockGuard<'a> {
88 lock: &'a StaticNativeMutex
91 pub static NATIVE_MUTEX_INIT: StaticNativeMutex = StaticNativeMutex {
92 inner: imp::MUTEX_INIT,
95 impl StaticNativeMutex {
96 /// Creates a new mutex.
98 /// Note that a mutex created in this way needs to be explicit
99 /// freed with a call to `destroy` or it will leak.
100 /// Also it is important to avoid locking until mutex has stopped moving
101 pub unsafe fn new() -> StaticNativeMutex {
102 StaticNativeMutex { inner: imp::Mutex::new() }
105 /// Acquires this lock. This assumes that the current thread does not
106 /// already hold the lock.
111 /// use std::rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
112 /// static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
114 /// let _guard = LOCK.lock();
115 /// // critical section...
116 /// } // automatically unlocked in `_guard`'s destructor
118 pub unsafe fn lock<'a>(&'a self) -> LockGuard<'a> {
121 LockGuard { lock: self }
124 /// Attempts to acquire the lock. The value returned is `Some` if
125 /// the attempt succeeded.
126 pub unsafe fn trylock<'a>(&'a self) -> Option<LockGuard<'a>> {
127 if self.inner.trylock() {
128 Some(LockGuard { lock: self })
134 /// Acquire the lock without creating a `LockGuard`.
136 /// These needs to be paired with a call to `.unlock_noguard`. Prefer using
138 pub unsafe fn lock_noguard(&self) { self.inner.lock() }
140 /// Attempts to acquire the lock without creating a
141 /// `LockGuard`. The value returned is whether the lock was
144 /// If `true` is returned, this needs to be paired with a call to
145 /// `.unlock_noguard`. Prefer using `.trylock`.
146 pub unsafe fn trylock_noguard(&self) -> bool {
150 /// Unlocks the lock. This assumes that the current thread already holds the
152 pub unsafe fn unlock_noguard(&self) { self.inner.unlock() }
154 /// Block on the internal condition variable.
156 /// This function assumes that the lock is already held. Prefer
157 /// using `LockGuard.wait` since that guarantees that the lock is
159 pub unsafe fn wait_noguard(&self) { self.inner.wait() }
161 /// Signals a thread in `wait` to wake up
162 pub unsafe fn signal_noguard(&self) { self.inner.signal() }
164 /// This function is especially unsafe because there are no guarantees made
165 /// that no other thread is currently holding the lock or waiting on the
166 /// condition variable contained inside.
167 pub unsafe fn destroy(&self) { self.inner.destroy() }
171 /// Creates a new mutex.
173 /// The user must be careful to ensure the mutex is not locked when its is
175 /// Also it is important to avoid locking until mutex has stopped moving
176 pub unsafe fn new() -> NativeMutex {
177 NativeMutex { inner: StaticNativeMutex::new() }
180 /// Acquires this lock. This assumes that the current thread does not
181 /// already hold the lock.
185 /// use std::rt::mutex::NativeMutex;
187 /// let mut lock = NativeMutex::new();
190 /// let _guard = lock.lock();
191 /// // critical section...
192 /// } // automatically unlocked in `_guard`'s destructor
195 pub unsafe fn lock<'a>(&'a self) -> LockGuard<'a> {
199 /// Attempts to acquire the lock. The value returned is `Some` if
200 /// the attempt succeeded.
201 pub unsafe fn trylock<'a>(&'a self) -> Option<LockGuard<'a>> {
205 /// Acquire the lock without creating a `LockGuard`.
207 /// These needs to be paired with a call to `.unlock_noguard`. Prefer using
209 pub unsafe fn lock_noguard(&self) { self.inner.lock_noguard() }
211 /// Attempts to acquire the lock without creating a
212 /// `LockGuard`. The value returned is whether the lock was
215 /// If `true` is returned, this needs to be paired with a call to
216 /// `.unlock_noguard`. Prefer using `.trylock`.
217 pub unsafe fn trylock_noguard(&self) -> bool {
218 self.inner.trylock_noguard()
221 /// Unlocks the lock. This assumes that the current thread already holds the
223 pub unsafe fn unlock_noguard(&self) { self.inner.unlock_noguard() }
225 /// Block on the internal condition variable.
227 /// This function assumes that the lock is already held. Prefer
228 /// using `LockGuard.wait` since that guarantees that the lock is
230 pub unsafe fn wait_noguard(&self) { self.inner.wait_noguard() }
232 /// Signals a thread in `wait` to wake up
233 pub unsafe fn signal_noguard(&self) { self.inner.signal_noguard() }
236 impl Drop for NativeMutex {
238 unsafe {self.inner.destroy()}
242 impl<'a> LockGuard<'a> {
243 /// Block on the internal condition variable.
244 pub unsafe fn wait(&self) {
245 self.lock.wait_noguard()
248 /// Signals a thread in `wait` to wake up.
249 pub unsafe fn signal(&self) {
250 self.lock.signal_noguard()
255 impl<'a> Drop for LockGuard<'a> {
257 unsafe {self.lock.unlock_noguard()}
264 use self::os::{PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER,
265 pthread_mutex_t, pthread_cond_t};
266 use core::ty::Unsafe;
267 use core::kinds::marker;
269 type pthread_mutexattr_t = libc::c_void;
270 type pthread_condattr_t = libc::c_void;
272 #[cfg(target_os = "freebsd")]
276 pub type pthread_mutex_t = *libc::c_void;
277 pub type pthread_cond_t = *libc::c_void;
279 pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t =
280 0 as pthread_mutex_t;
281 pub static PTHREAD_COND_INITIALIZER: pthread_cond_t =
285 #[cfg(target_os = "macos")]
289 #[cfg(target_arch = "x86_64")]
290 static __PTHREAD_MUTEX_SIZE__: uint = 56;
291 #[cfg(target_arch = "x86_64")]
292 static __PTHREAD_COND_SIZE__: uint = 40;
293 #[cfg(target_arch = "x86")]
294 static __PTHREAD_MUTEX_SIZE__: uint = 40;
295 #[cfg(target_arch = "x86")]
296 static __PTHREAD_COND_SIZE__: uint = 24;
298 static _PTHREAD_MUTEX_SIG_init: libc::c_long = 0x32AAABA7;
299 static _PTHREAD_COND_SIG_init: libc::c_long = 0x3CB0B1BB;
301 pub struct pthread_mutex_t {
303 __opaque: [u8, ..__PTHREAD_MUTEX_SIZE__],
305 pub struct pthread_cond_t {
307 __opaque: [u8, ..__PTHREAD_COND_SIZE__],
310 pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
311 __sig: _PTHREAD_MUTEX_SIG_init,
312 __opaque: [0, ..__PTHREAD_MUTEX_SIZE__],
314 pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
315 __sig: _PTHREAD_COND_SIG_init,
316 __opaque: [0, ..__PTHREAD_COND_SIZE__],
320 #[cfg(target_os = "linux")]
324 // minus 8 because we have an 'align' field
325 #[cfg(target_arch = "x86_64")]
326 static __SIZEOF_PTHREAD_MUTEX_T: uint = 40 - 8;
327 #[cfg(target_arch = "x86")]
328 static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
329 #[cfg(target_arch = "arm")]
330 static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
331 #[cfg(target_arch = "mips")]
332 static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
333 #[cfg(target_arch = "x86_64")]
334 static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
335 #[cfg(target_arch = "x86")]
336 static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
337 #[cfg(target_arch = "arm")]
338 static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
339 #[cfg(target_arch = "mips")]
340 static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
342 pub struct pthread_mutex_t {
343 __align: libc::c_longlong,
344 size: [u8, ..__SIZEOF_PTHREAD_MUTEX_T],
346 pub struct pthread_cond_t {
347 __align: libc::c_longlong,
348 size: [u8, ..__SIZEOF_PTHREAD_COND_T],
351 pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
353 size: [0, ..__SIZEOF_PTHREAD_MUTEX_T],
355 pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
357 size: [0, ..__SIZEOF_PTHREAD_COND_T],
360 #[cfg(target_os = "android")]
364 pub struct pthread_mutex_t { value: libc::c_int }
365 pub struct pthread_cond_t { value: libc::c_int }
367 pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
370 pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
376 lock: Unsafe<pthread_mutex_t>,
377 cond: Unsafe<pthread_cond_t>,
380 pub static MUTEX_INIT: Mutex = Mutex {
382 value: PTHREAD_MUTEX_INITIALIZER,
383 marker1: marker::InvariantType,
386 value: PTHREAD_COND_INITIALIZER,
387 marker1: marker::InvariantType,
392 pub unsafe fn new() -> Mutex {
393 // As mutex might be moved and address is changing it
394 // is better to avoid initialization of potentially
395 // opaque OS data before it landed
397 lock: Unsafe::new(PTHREAD_MUTEX_INITIALIZER),
398 cond: Unsafe::new(PTHREAD_COND_INITIALIZER),
404 pub unsafe fn lock(&self) { pthread_mutex_lock(self.lock.get()); }
405 pub unsafe fn unlock(&self) { pthread_mutex_unlock(self.lock.get()); }
406 pub unsafe fn signal(&self) { pthread_cond_signal(self.cond.get()); }
407 pub unsafe fn wait(&self) {
408 pthread_cond_wait(self.cond.get(), self.lock.get());
410 pub unsafe fn trylock(&self) -> bool {
411 pthread_mutex_trylock(self.lock.get()) == 0
413 pub unsafe fn destroy(&self) {
414 pthread_mutex_destroy(self.lock.get());
415 pthread_cond_destroy(self.cond.get());
420 fn pthread_mutex_destroy(lock: *mut pthread_mutex_t) -> libc::c_int;
421 fn pthread_cond_destroy(cond: *mut pthread_cond_t) -> libc::c_int;
422 fn pthread_mutex_lock(lock: *mut pthread_mutex_t) -> libc::c_int;
423 fn pthread_mutex_trylock(lock: *mut pthread_mutex_t) -> libc::c_int;
424 fn pthread_mutex_unlock(lock: *mut pthread_mutex_t) -> libc::c_int;
426 fn pthread_cond_wait(cond: *mut pthread_cond_t,
427 lock: *mut pthread_mutex_t) -> libc::c_int;
428 fn pthread_cond_signal(cond: *mut pthread_cond_t) -> libc::c_int;
434 use alloc::libc_heap::malloc_raw;
437 use libc::{HANDLE, BOOL, LPSECURITY_ATTRIBUTES, c_void, DWORD, LPCSTR};
440 type LPCRITICAL_SECTION = *mut c_void;
441 static SPIN_COUNT: DWORD = 4000;
442 #[cfg(target_arch = "x86")]
443 static CRIT_SECTION_SIZE: uint = 24;
444 #[cfg(target_arch = "x86_64")]
445 static CRIT_SECTION_SIZE: uint = 40;
448 // pointers for the lock/cond handles, atomically updated
449 lock: atomics::AtomicUint,
450 cond: atomics::AtomicUint,
453 pub static MUTEX_INIT: Mutex = Mutex {
454 lock: atomics::INIT_ATOMIC_UINT,
455 cond: atomics::INIT_ATOMIC_UINT,
459 pub unsafe fn new() -> Mutex {
461 lock: atomics::AtomicUint::new(init_lock()),
462 cond: atomics::AtomicUint::new(init_cond()),
465 pub unsafe fn lock(&self) {
466 EnterCriticalSection(self.getlock() as LPCRITICAL_SECTION)
468 pub unsafe fn trylock(&self) -> bool {
469 TryEnterCriticalSection(self.getlock() as LPCRITICAL_SECTION) != 0
471 pub unsafe fn unlock(&self) {
472 LeaveCriticalSection(self.getlock() as LPCRITICAL_SECTION)
475 pub unsafe fn wait(&self) {
477 WaitForSingleObject(self.getcond() as HANDLE, libc::INFINITE);
481 pub unsafe fn signal(&self) {
482 assert!(SetEvent(self.getcond() as HANDLE) != 0);
485 /// This function is especially unsafe because there are no guarantees made
486 /// that no other thread is currently holding the lock or waiting on the
487 /// condition variable contained inside.
488 pub unsafe fn destroy(&self) {
489 let lock = self.lock.swap(0, atomics::SeqCst);
490 let cond = self.cond.swap(0, atomics::SeqCst);
491 if lock != 0 { free_lock(lock) }
492 if cond != 0 { free_cond(cond) }
495 unsafe fn getlock(&self) -> *mut c_void {
496 match self.lock.load(atomics::SeqCst) {
498 n => return n as *mut c_void
500 let lock = init_lock();
501 match self.lock.compare_and_swap(0, lock, atomics::SeqCst) {
502 0 => return lock as *mut c_void,
506 return self.lock.load(atomics::SeqCst) as *mut c_void;
509 unsafe fn getcond(&self) -> *mut c_void {
510 match self.cond.load(atomics::SeqCst) {
512 n => return n as *mut c_void
514 let cond = init_cond();
515 match self.cond.compare_and_swap(0, cond, atomics::SeqCst) {
516 0 => return cond as *mut c_void,
520 return self.cond.load(atomics::SeqCst) as *mut c_void;
524 pub unsafe fn init_lock() -> uint {
525 let block = malloc_raw(CRIT_SECTION_SIZE as uint) as *mut c_void;
526 InitializeCriticalSectionAndSpinCount(block, SPIN_COUNT);
527 return block as uint;
530 pub unsafe fn init_cond() -> uint {
531 return CreateEventA(ptr::mut_null(), libc::FALSE, libc::FALSE,
532 ptr::null()) as uint;
535 pub unsafe fn free_lock(h: uint) {
536 DeleteCriticalSection(h as LPCRITICAL_SECTION);
537 libc::free(h as *mut c_void);
540 pub unsafe fn free_cond(h: uint) {
541 let block = h as HANDLE;
542 libc::CloseHandle(block);
545 #[allow(non_snake_case_functions)]
547 fn CreateEventA(lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
550 lpName: LPCSTR) -> HANDLE;
551 fn InitializeCriticalSectionAndSpinCount(
552 lpCriticalSection: LPCRITICAL_SECTION,
553 dwSpinCount: DWORD) -> BOOL;
554 fn DeleteCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
555 fn EnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
556 fn LeaveCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
557 fn TryEnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION) -> BOOL;
558 fn SetEvent(hEvent: HANDLE) -> BOOL;
559 fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
568 use super::{StaticNativeMutex, NATIVE_MUTEX_INIT};
569 use std::rt::thread::Thread;
573 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
575 let _guard = lock.lock();
581 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
583 let guard = lock.lock();
584 let t = Thread::start(proc() {
585 let guard = lock.lock();
596 fn smoke_lock_noguard() {
597 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
600 lock.unlock_noguard();
605 fn smoke_cond_noguard() {
606 static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
609 let t = Thread::start(proc() {
611 lock.signal_noguard();
612 lock.unlock_noguard();
615 lock.unlock_noguard();
622 fn destroy_immediately() {
624 let m = StaticNativeMutex::new();