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 sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering};
14 use alloc::{self, heap};
19 const SPIN_COUNT: DWORD = 4000;
21 pub struct Mutex { inner: AtomicUint }
23 pub const MUTEX_INIT: Mutex = Mutex { inner: ATOMIC_UINT_INIT };
25 unsafe impl Sync for Mutex {}
28 pub unsafe fn raw(m: &Mutex) -> ffi::LPCRITICAL_SECTION {
34 pub unsafe fn new() -> Mutex {
35 Mutex { inner: AtomicUint::new(init_lock() as uint) }
38 pub unsafe fn lock(&self) {
39 ffi::EnterCriticalSection(self.get())
42 pub unsafe fn try_lock(&self) -> bool {
43 ffi::TryEnterCriticalSection(self.get()) != 0
46 pub unsafe fn unlock(&self) {
47 ffi::LeaveCriticalSection(self.get())
49 pub unsafe fn destroy(&self) {
50 let lock = self.inner.swap(0, Ordering::SeqCst);
51 if lock != 0 { free_lock(lock as ffi::LPCRITICAL_SECTION) }
54 unsafe fn get(&self) -> ffi::LPCRITICAL_SECTION {
55 match self.inner.load(Ordering::SeqCst) {
57 n => return n as ffi::LPCRITICAL_SECTION
59 let lock = init_lock();
60 match self.inner.compare_and_swap(0, lock as uint, Ordering::SeqCst) {
61 0 => return lock as ffi::LPCRITICAL_SECTION,
65 return self.inner.load(Ordering::SeqCst) as ffi::LPCRITICAL_SECTION;
69 unsafe fn init_lock() -> ffi::LPCRITICAL_SECTION {
70 let block = heap::allocate(ffi::CRITICAL_SECTION_SIZE, 8)
71 as ffi::LPCRITICAL_SECTION;
72 if block.is_null() { alloc::oom() }
73 ffi::InitializeCriticalSectionAndSpinCount(block, SPIN_COUNT);
77 unsafe fn free_lock(h: ffi::LPCRITICAL_SECTION) {
78 ffi::DeleteCriticalSection(h);
79 heap::deallocate(h as *mut _, ffi::CRITICAL_SECTION_SIZE, 8);