]> git.lizzy.rs Git - rust.git/blob - src/librustrt/mutex.rs
auto merge of #15941 : treeman/rust/doc-lru, r=alexcrichton
[rust.git] / src / librustrt / mutex.rs
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.
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 //! A native mutex and condition variable type.
12 //!
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.
18 //!
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.
24 //!
25 //! The non-static `NativeMutex` type does have a destructor, but cannot be
26 //! statically initialized.
27 //!
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.
32 //!
33 //! # Example
34 //!
35 //! ```rust
36 //! use std::rt::mutex::{NativeMutex, StaticNativeMutex, NATIVE_MUTEX_INIT};
37 //!
38 //! // Use a statically initialized mutex
39 //! static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
40 //!
41 //! unsafe {
42 //!     let _guard = LOCK.lock();
43 //! } // automatically unlocked here
44 //!
45 //! // Use a normally initialized mutex
46 //! unsafe {
47 //!     let mut lock = NativeMutex::new();
48 //!
49 //!     {
50 //!         let _guard = lock.lock();
51 //!     } // unlocked here
52 //!
53 //!     // sometimes the RAII guard isn't appropriate
54 //!     lock.lock_noguard();
55 //!     lock.unlock_noguard();
56 //! } // `lock` is deallocated here
57 //! ```
58
59 #![allow(non_camel_case_types)]
60
61 use core::prelude::*;
62
63 /// A native mutex suitable for storing in statics (that is, it has
64 /// the `destroy` method rather than a destructor).
65 ///
66 /// Prefer the `NativeMutex` type where possible, since that does not
67 /// require manual deallocation.
68 pub struct StaticNativeMutex {
69     inner: imp::Mutex,
70 }
71
72 /// A native mutex with a destructor for clean-up.
73 ///
74 /// See `StaticNativeMutex` for a version that is suitable for storing in
75 /// statics.
76 pub struct NativeMutex {
77     inner: StaticNativeMutex
78 }
79
80 /// Automatically unlocks the mutex that it was created from on
81 /// destruction.
82 ///
83 /// Using this makes lock-based code resilient to unwinding/task
84 /// failure, because the lock will be automatically unlocked even
85 /// then.
86 #[must_use]
87 pub struct LockGuard<'a> {
88     lock: &'a StaticNativeMutex
89 }
90
91 pub static NATIVE_MUTEX_INIT: StaticNativeMutex = StaticNativeMutex {
92     inner: imp::MUTEX_INIT,
93 };
94
95 impl StaticNativeMutex {
96     /// Creates a new mutex.
97     ///
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() }
103     }
104
105     /// Acquires this lock. This assumes that the current thread does not
106     /// already hold the lock.
107     ///
108     /// # Example
109     ///
110     /// ```rust
111     /// use std::rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
112     /// static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
113     /// unsafe {
114     ///     let _guard = LOCK.lock();
115     ///     // critical section...
116     /// } // automatically unlocked in `_guard`'s destructor
117     /// ```
118     ///
119     /// # Unsafety
120     ///
121     /// This method is unsafe because it will not function correctly if this
122     /// mutex has been *moved* since it was last used. The mutex can move an
123     /// arbitrary number of times before its first usage, but once a mutex has
124     /// been used once it is no longer allowed to move (or otherwise it invokes
125     /// undefined behavior).
126     ///
127     /// Additionally, this type does not take into account any form of
128     /// scheduling model. This will unconditionally block the *os thread* which
129     /// is not always desired.
130     pub unsafe fn lock<'a>(&'a self) -> LockGuard<'a> {
131         self.inner.lock();
132
133         LockGuard { lock: self }
134     }
135
136     /// Attempts to acquire the lock. The value returned is `Some` if
137     /// the attempt succeeded.
138     ///
139     /// # Unsafety
140     ///
141     /// This method is unsafe for the same reasons as `lock`.
142     pub unsafe fn trylock<'a>(&'a self) -> Option<LockGuard<'a>> {
143         if self.inner.trylock() {
144             Some(LockGuard { lock: self })
145         } else {
146             None
147         }
148     }
149
150     /// Acquire the lock without creating a `LockGuard`.
151     ///
152     /// These needs to be paired with a call to `.unlock_noguard`. Prefer using
153     /// `.lock`.
154     ///
155     /// # Unsafety
156     ///
157     /// This method is unsafe for the same reasons as `lock`. Additionally, this
158     /// does not guarantee that the mutex will ever be unlocked, and it is
159     /// undefined to drop an already-locked mutex.
160     pub unsafe fn lock_noguard(&self) { self.inner.lock() }
161
162     /// Attempts to acquire the lock without creating a
163     /// `LockGuard`. The value returned is whether the lock was
164     /// acquired or not.
165     ///
166     /// If `true` is returned, this needs to be paired with a call to
167     /// `.unlock_noguard`. Prefer using `.trylock`.
168     ///
169     /// # Unsafety
170     ///
171     /// This method is unsafe for the same reasons as `lock_noguard`.
172     pub unsafe fn trylock_noguard(&self) -> bool {
173         self.inner.trylock()
174     }
175
176     /// Unlocks the lock. This assumes that the current thread already holds the
177     /// lock.
178     ///
179     /// # Unsafety
180     ///
181     /// This method is unsafe for the same reasons as `lock`. Additionally, it
182     /// is not guaranteed that this is unlocking a previously locked mutex. It
183     /// is undefined to unlock an unlocked mutex.
184     pub unsafe fn unlock_noguard(&self) { self.inner.unlock() }
185
186     /// Block on the internal condition variable.
187     ///
188     /// This function assumes that the lock is already held. Prefer
189     /// using `LockGuard.wait` since that guarantees that the lock is
190     /// held.
191     ///
192     /// # Unsafety
193     ///
194     /// This method is unsafe for the same reasons as `lock`. Additionally, this
195     /// is unsafe because the mutex may not be currently locked.
196     pub unsafe fn wait_noguard(&self) { self.inner.wait() }
197
198     /// Signals a thread in `wait` to wake up
199     ///
200     /// # Unsafety
201     ///
202     /// This method is unsafe for the same reasons as `lock`. Additionally, this
203     /// is unsafe because the mutex may not be currently locked.
204     pub unsafe fn signal_noguard(&self) { self.inner.signal() }
205
206     /// This function is especially unsafe because there are no guarantees made
207     /// that no other thread is currently holding the lock or waiting on the
208     /// condition variable contained inside.
209     pub unsafe fn destroy(&self) { self.inner.destroy() }
210 }
211
212 impl NativeMutex {
213     /// Creates a new mutex.
214     ///
215     /// The user must be careful to ensure the mutex is not locked when its is
216     /// being destroyed.
217     /// Also it is important to avoid locking until mutex has stopped moving
218     pub unsafe fn new() -> NativeMutex {
219         NativeMutex { inner: StaticNativeMutex::new() }
220     }
221
222     /// Acquires this lock. This assumes that the current thread does not
223     /// already hold the lock.
224     ///
225     /// # Example
226     ///
227     /// ```rust
228     /// use std::rt::mutex::NativeMutex;
229     /// unsafe {
230     ///     let mut lock = NativeMutex::new();
231     ///
232     ///     {
233     ///         let _guard = lock.lock();
234     ///         // critical section...
235     ///     } // automatically unlocked in `_guard`'s destructor
236     /// }
237     /// ```
238     ///
239     /// # Unsafety
240     ///
241     /// This method is unsafe due to the same reasons as
242     /// `StaticNativeMutex::lock`.
243     pub unsafe fn lock<'a>(&'a self) -> LockGuard<'a> {
244         self.inner.lock()
245     }
246
247     /// Attempts to acquire the lock. The value returned is `Some` if
248     /// the attempt succeeded.
249     ///
250     /// # Unsafety
251     ///
252     /// This method is unsafe due to the same reasons as
253     /// `StaticNativeMutex::trylock`.
254     pub unsafe fn trylock<'a>(&'a self) -> Option<LockGuard<'a>> {
255         self.inner.trylock()
256     }
257
258     /// Acquire the lock without creating a `LockGuard`.
259     ///
260     /// These needs to be paired with a call to `.unlock_noguard`. Prefer using
261     /// `.lock`.
262     ///
263     /// # Unsafety
264     ///
265     /// This method is unsafe due to the same reasons as
266     /// `StaticNativeMutex::lock_noguard`.
267     pub unsafe fn lock_noguard(&self) { self.inner.lock_noguard() }
268
269     /// Attempts to acquire the lock without creating a
270     /// `LockGuard`. The value returned is whether the lock was
271     /// acquired or not.
272     ///
273     /// If `true` is returned, this needs to be paired with a call to
274     /// `.unlock_noguard`. Prefer using `.trylock`.
275     ///
276     /// # Unsafety
277     ///
278     /// This method is unsafe due to the same reasons as
279     /// `StaticNativeMutex::trylock_noguard`.
280     pub unsafe fn trylock_noguard(&self) -> bool {
281         self.inner.trylock_noguard()
282     }
283
284     /// Unlocks the lock. This assumes that the current thread already holds the
285     /// lock.
286     ///
287     /// # Unsafety
288     ///
289     /// This method is unsafe due to the same reasons as
290     /// `StaticNativeMutex::unlock_noguard`.
291     pub unsafe fn unlock_noguard(&self) { self.inner.unlock_noguard() }
292
293     /// Block on the internal condition variable.
294     ///
295     /// This function assumes that the lock is already held. Prefer
296     /// using `LockGuard.wait` since that guarantees that the lock is
297     /// held.
298     ///
299     /// # Unsafety
300     ///
301     /// This method is unsafe due to the same reasons as
302     /// `StaticNativeMutex::wait_noguard`.
303     pub unsafe fn wait_noguard(&self) { self.inner.wait_noguard() }
304
305     /// Signals a thread in `wait` to wake up
306     ///
307     /// # Unsafety
308     ///
309     /// This method is unsafe due to the same reasons as
310     /// `StaticNativeMutex::signal_noguard`.
311     pub unsafe fn signal_noguard(&self) { self.inner.signal_noguard() }
312 }
313
314 impl Drop for NativeMutex {
315     fn drop(&mut self) {
316         unsafe {self.inner.destroy()}
317     }
318 }
319
320 impl<'a> LockGuard<'a> {
321     /// Block on the internal condition variable.
322     pub unsafe fn wait(&self) {
323         self.lock.wait_noguard()
324     }
325
326     /// Signals a thread in `wait` to wake up.
327     pub unsafe fn signal(&self) {
328         self.lock.signal_noguard()
329     }
330 }
331
332 #[unsafe_destructor]
333 impl<'a> Drop for LockGuard<'a> {
334     fn drop(&mut self) {
335         unsafe {self.lock.unlock_noguard()}
336     }
337 }
338
339 #[cfg(unix)]
340 mod imp {
341     use libc;
342     use self::os::{PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER,
343                    pthread_mutex_t, pthread_cond_t};
344     use core::cell::UnsafeCell;
345
346     type pthread_mutexattr_t = libc::c_void;
347     type pthread_condattr_t = libc::c_void;
348
349     #[cfg(target_os = "freebsd")]
350     mod os {
351         use libc;
352
353         pub type pthread_mutex_t = *mut libc::c_void;
354         pub type pthread_cond_t = *mut libc::c_void;
355
356         pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t =
357             0 as pthread_mutex_t;
358         pub static PTHREAD_COND_INITIALIZER: pthread_cond_t =
359             0 as pthread_cond_t;
360     }
361
362     #[cfg(target_os = "macos")]
363     #[cfg(target_os = "ios")]
364     mod os {
365         use libc;
366
367         #[cfg(target_arch = "x86_64")]
368         static __PTHREAD_MUTEX_SIZE__: uint = 56;
369         #[cfg(target_arch = "x86_64")]
370         static __PTHREAD_COND_SIZE__: uint = 40;
371         #[cfg(target_arch = "x86")]
372         static __PTHREAD_MUTEX_SIZE__: uint = 40;
373         #[cfg(target_arch = "x86")]
374         static __PTHREAD_COND_SIZE__: uint = 24;
375         #[cfg(target_arch = "arm")]
376         static __PTHREAD_MUTEX_SIZE__: uint = 40;
377         #[cfg(target_arch = "arm")]
378         static __PTHREAD_COND_SIZE__: uint = 24;
379
380         static _PTHREAD_MUTEX_SIG_init: libc::c_long = 0x32AAABA7;
381         static _PTHREAD_COND_SIG_init: libc::c_long = 0x3CB0B1BB;
382
383         #[repr(C)]
384         pub struct pthread_mutex_t {
385             __sig: libc::c_long,
386             __opaque: [u8, ..__PTHREAD_MUTEX_SIZE__],
387         }
388         #[repr(C)]
389         pub struct pthread_cond_t {
390             __sig: libc::c_long,
391             __opaque: [u8, ..__PTHREAD_COND_SIZE__],
392         }
393
394         pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
395             __sig: _PTHREAD_MUTEX_SIG_init,
396             __opaque: [0, ..__PTHREAD_MUTEX_SIZE__],
397         };
398         pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
399             __sig: _PTHREAD_COND_SIG_init,
400             __opaque: [0, ..__PTHREAD_COND_SIZE__],
401         };
402     }
403
404     #[cfg(target_os = "linux")]
405     mod os {
406         use libc;
407
408         // minus 8 because we have an 'align' field
409         #[cfg(target_arch = "x86_64")]
410         static __SIZEOF_PTHREAD_MUTEX_T: uint = 40 - 8;
411         #[cfg(target_arch = "x86")]
412         static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
413         #[cfg(target_arch = "arm")]
414         static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
415         #[cfg(target_arch = "mips")]
416         static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
417         #[cfg(target_arch = "mipsel")]
418         static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
419         #[cfg(target_arch = "x86_64")]
420         static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
421         #[cfg(target_arch = "x86")]
422         static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
423         #[cfg(target_arch = "arm")]
424         static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
425         #[cfg(target_arch = "mips")]
426         static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
427         #[cfg(target_arch = "mipsel")]
428         static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
429
430         #[repr(C)]
431         pub struct pthread_mutex_t {
432             __align: libc::c_longlong,
433             size: [u8, ..__SIZEOF_PTHREAD_MUTEX_T],
434         }
435         #[repr(C)]
436         pub struct pthread_cond_t {
437             __align: libc::c_longlong,
438             size: [u8, ..__SIZEOF_PTHREAD_COND_T],
439         }
440
441         pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
442             __align: 0,
443             size: [0, ..__SIZEOF_PTHREAD_MUTEX_T],
444         };
445         pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
446             __align: 0,
447             size: [0, ..__SIZEOF_PTHREAD_COND_T],
448         };
449     }
450     #[cfg(target_os = "android")]
451     mod os {
452         use libc;
453
454         #[repr(C)]
455         pub struct pthread_mutex_t { value: libc::c_int }
456         #[repr(C)]
457         pub struct pthread_cond_t { value: libc::c_int }
458
459         pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
460             value: 0,
461         };
462         pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
463             value: 0,
464         };
465     }
466
467     pub struct Mutex {
468         lock: UnsafeCell<pthread_mutex_t>,
469         cond: UnsafeCell<pthread_cond_t>,
470     }
471
472     pub static MUTEX_INIT: Mutex = Mutex {
473         lock: UnsafeCell { value: PTHREAD_MUTEX_INITIALIZER },
474         cond: UnsafeCell { value: PTHREAD_COND_INITIALIZER },
475     };
476
477     impl Mutex {
478         pub unsafe fn new() -> Mutex {
479             // As mutex might be moved and address is changing it
480             // is better to avoid initialization of potentially
481             // opaque OS data before it landed
482             let m = Mutex {
483                 lock: UnsafeCell::new(PTHREAD_MUTEX_INITIALIZER),
484                 cond: UnsafeCell::new(PTHREAD_COND_INITIALIZER),
485             };
486
487             return m;
488         }
489
490         pub unsafe fn lock(&self) { pthread_mutex_lock(self.lock.get()); }
491         pub unsafe fn unlock(&self) { pthread_mutex_unlock(self.lock.get()); }
492         pub unsafe fn signal(&self) { pthread_cond_signal(self.cond.get()); }
493         pub unsafe fn wait(&self) {
494             pthread_cond_wait(self.cond.get(), self.lock.get());
495         }
496         pub unsafe fn trylock(&self) -> bool {
497             pthread_mutex_trylock(self.lock.get()) == 0
498         }
499         pub unsafe fn destroy(&self) {
500             pthread_mutex_destroy(self.lock.get());
501             pthread_cond_destroy(self.cond.get());
502         }
503     }
504
505     extern {
506         fn pthread_mutex_destroy(lock: *mut pthread_mutex_t) -> libc::c_int;
507         fn pthread_cond_destroy(cond: *mut pthread_cond_t) -> libc::c_int;
508         fn pthread_mutex_lock(lock: *mut pthread_mutex_t) -> libc::c_int;
509         fn pthread_mutex_trylock(lock: *mut pthread_mutex_t) -> libc::c_int;
510         fn pthread_mutex_unlock(lock: *mut pthread_mutex_t) -> libc::c_int;
511
512         fn pthread_cond_wait(cond: *mut pthread_cond_t,
513                              lock: *mut pthread_mutex_t) -> libc::c_int;
514         fn pthread_cond_signal(cond: *mut pthread_cond_t) -> libc::c_int;
515     }
516 }
517
518 #[cfg(windows)]
519 mod imp {
520     use alloc::libc_heap::malloc_raw;
521     use core::atomics;
522     use core::ptr;
523     use libc::{HANDLE, BOOL, LPSECURITY_ATTRIBUTES, c_void, DWORD, LPCSTR};
524     use libc;
525
526     type LPCRITICAL_SECTION = *mut c_void;
527     static SPIN_COUNT: DWORD = 4000;
528     #[cfg(target_arch = "x86")]
529     static CRIT_SECTION_SIZE: uint = 24;
530     #[cfg(target_arch = "x86_64")]
531     static CRIT_SECTION_SIZE: uint = 40;
532
533     pub struct Mutex {
534         // pointers for the lock/cond handles, atomically updated
535         lock: atomics::AtomicUint,
536         cond: atomics::AtomicUint,
537     }
538
539     pub static MUTEX_INIT: Mutex = Mutex {
540         lock: atomics::INIT_ATOMIC_UINT,
541         cond: atomics::INIT_ATOMIC_UINT,
542     };
543
544     impl Mutex {
545         pub unsafe fn new() -> Mutex {
546             Mutex {
547                 lock: atomics::AtomicUint::new(init_lock()),
548                 cond: atomics::AtomicUint::new(init_cond()),
549             }
550         }
551         pub unsafe fn lock(&self) {
552             EnterCriticalSection(self.getlock() as LPCRITICAL_SECTION)
553         }
554         pub unsafe fn trylock(&self) -> bool {
555             TryEnterCriticalSection(self.getlock() as LPCRITICAL_SECTION) != 0
556         }
557         pub unsafe fn unlock(&self) {
558             LeaveCriticalSection(self.getlock() as LPCRITICAL_SECTION)
559         }
560
561         pub unsafe fn wait(&self) {
562             self.unlock();
563             WaitForSingleObject(self.getcond() as HANDLE, libc::INFINITE);
564             self.lock();
565         }
566
567         pub unsafe fn signal(&self) {
568             assert!(SetEvent(self.getcond() as HANDLE) != 0);
569         }
570
571         /// This function is especially unsafe because there are no guarantees made
572         /// that no other thread is currently holding the lock or waiting on the
573         /// condition variable contained inside.
574         pub unsafe fn destroy(&self) {
575             let lock = self.lock.swap(0, atomics::SeqCst);
576             let cond = self.cond.swap(0, atomics::SeqCst);
577             if lock != 0 { free_lock(lock) }
578             if cond != 0 { free_cond(cond) }
579         }
580
581         unsafe fn getlock(&self) -> *mut c_void {
582             match self.lock.load(atomics::SeqCst) {
583                 0 => {}
584                 n => return n as *mut c_void
585             }
586             let lock = init_lock();
587             match self.lock.compare_and_swap(0, lock, atomics::SeqCst) {
588                 0 => return lock as *mut c_void,
589                 _ => {}
590             }
591             free_lock(lock);
592             return self.lock.load(atomics::SeqCst) as *mut c_void;
593         }
594
595         unsafe fn getcond(&self) -> *mut c_void {
596             match self.cond.load(atomics::SeqCst) {
597                 0 => {}
598                 n => return n as *mut c_void
599             }
600             let cond = init_cond();
601             match self.cond.compare_and_swap(0, cond, atomics::SeqCst) {
602                 0 => return cond as *mut c_void,
603                 _ => {}
604             }
605             free_cond(cond);
606             return self.cond.load(atomics::SeqCst) as *mut c_void;
607         }
608     }
609
610     pub unsafe fn init_lock() -> uint {
611         let block = malloc_raw(CRIT_SECTION_SIZE as uint) as *mut c_void;
612         InitializeCriticalSectionAndSpinCount(block, SPIN_COUNT);
613         return block as uint;
614     }
615
616     pub unsafe fn init_cond() -> uint {
617         return CreateEventA(ptr::mut_null(), libc::FALSE, libc::FALSE,
618                             ptr::null()) as uint;
619     }
620
621     pub unsafe fn free_lock(h: uint) {
622         DeleteCriticalSection(h as LPCRITICAL_SECTION);
623         libc::free(h as *mut c_void);
624     }
625
626     pub unsafe fn free_cond(h: uint) {
627         let block = h as HANDLE;
628         libc::CloseHandle(block);
629     }
630
631     #[allow(non_snake_case_functions)]
632     extern "system" {
633         fn CreateEventA(lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
634                         bManualReset: BOOL,
635                         bInitialState: BOOL,
636                         lpName: LPCSTR) -> HANDLE;
637         fn InitializeCriticalSectionAndSpinCount(
638                         lpCriticalSection: LPCRITICAL_SECTION,
639                         dwSpinCount: DWORD) -> BOOL;
640         fn DeleteCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
641         fn EnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
642         fn LeaveCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
643         fn TryEnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION) -> BOOL;
644         fn SetEvent(hEvent: HANDLE) -> BOOL;
645         fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
646     }
647 }
648
649 #[cfg(test)]
650 mod test {
651     use std::prelude::*;
652
653     use std::mem::drop;
654     use super::{StaticNativeMutex, NATIVE_MUTEX_INIT};
655     use std::rt::thread::Thread;
656
657     #[test]
658     fn smoke_lock() {
659         static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
660         unsafe {
661             let _guard = lock.lock();
662         }
663     }
664
665     #[test]
666     fn smoke_cond() {
667         static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
668         unsafe {
669             let guard = lock.lock();
670             let t = Thread::start(proc() {
671                 let guard = lock.lock();
672                 guard.signal();
673             });
674             guard.wait();
675             drop(guard);
676
677             t.join();
678         }
679     }
680
681     #[test]
682     fn smoke_lock_noguard() {
683         static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
684         unsafe {
685             lock.lock_noguard();
686             lock.unlock_noguard();
687         }
688     }
689
690     #[test]
691     fn smoke_cond_noguard() {
692         static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
693         unsafe {
694             lock.lock_noguard();
695             let t = Thread::start(proc() {
696                 lock.lock_noguard();
697                 lock.signal_noguard();
698                 lock.unlock_noguard();
699             });
700             lock.wait_noguard();
701             lock.unlock_noguard();
702
703             t.join();
704         }
705     }
706
707     #[test]
708     fn destroy_immediately() {
709         unsafe {
710             let m = StaticNativeMutex::new();
711             m.destroy();
712         }
713     }
714 }