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.
17 pub struct Mutex { inner: UnsafeCell<ffi::SRWLOCK> }
19 unsafe impl Send
for Mutex {}
20 unsafe impl Sync
for Mutex {}
23 pub unsafe fn raw(m
: &Mutex
) -> ffi
::PSRWLOCK
{
27 // So you might be asking why we're using SRWLock instead of CriticalSection?
29 // 1. SRWLock is several times faster than CriticalSection according to
30 // benchmarks performed on both Windows 8 and Windows 7.
32 // 2. CriticalSection allows recursive locking while SRWLock deadlocks. The Unix
33 // implementation deadlocks so consistency is preferred. See #19962 for more
36 // 3. While CriticalSection is fair and SRWLock is not, the current Rust policy
37 // is there there are no guarantees of fairness.
40 pub const fn new() -> Mutex
{
41 Mutex { inner: UnsafeCell::new(ffi::SRWLOCK_INIT) }
44 pub unsafe fn lock(&self) {
45 ffi
::AcquireSRWLockExclusive(self.inner
.get())
48 pub unsafe fn try_lock(&self) -> bool
{
49 ffi
::TryAcquireSRWLockExclusive(self.inner
.get()) != 0
52 pub unsafe fn unlock(&self) {
53 ffi
::ReleaseSRWLockExclusive(self.inner
.get())
56 pub unsafe fn destroy(&self) {
61 pub struct ReentrantMutex { inner: UnsafeCell<ffi::CRITICAL_SECTION> }
63 unsafe impl Send
for ReentrantMutex {}
64 unsafe impl Sync
for ReentrantMutex {}
67 pub unsafe fn uninitialized() -> ReentrantMutex
{
71 pub unsafe fn init(&mut self) {
72 ffi
::InitializeCriticalSection(self.inner
.get());
75 pub unsafe fn lock(&self) {
76 ffi
::EnterCriticalSection(self.inner
.get());
80 pub unsafe fn try_lock(&self) -> bool
{
81 ffi
::TryEnterCriticalSection(self.inner
.get()) != 0
84 pub unsafe fn unlock(&self) {
85 ffi
::LeaveCriticalSection(self.inner
.get());
88 pub unsafe fn destroy(&self) {
89 ffi
::DeleteCriticalSection(self.inner
.get());