Skip to content

Commit 504991c

Browse files
committed
Fix mutex impl detection for critical sections
Fixes #21.
1 parent 591bcb0 commit 504991c

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed

library/std/src/sys/windows/compat.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use crate::sync::atomic::Ordering;
2525
use crate::sys::c;
2626

2727
mod version;
28-
pub use version::{is_windows_nt, supports_async_io};
28+
pub use version::*;
2929

3030
// This uses a static initializer to preload some imported functions.
3131
// The CRT (C runtime) executes static initializers before `main`

library/std/src/sys/windows/compat/version.rs

+18-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,22 @@ use crate::sys::c;
22

33
static mut IS_NT: bool = true;
44
static mut SUPPORTS_ASYNC_IO: bool = true;
5+
static mut SUPPORTS_TRY_ENTER_CRITICAL_SECTION: bool = true;
56

67
pub fn init_windows_version_check() {
7-
// according to old MSDN info, the high-order bit is set only on 95/98/ME.
88
unsafe {
9-
IS_NT = c::GetVersion() < 0x8000_0000;
10-
SUPPORTS_ASYNC_IO = IS_NT && c::CancelIo::option().is_some();
9+
let version = c::GetVersion();
10+
let major = version as u8;
11+
12+
// according to old MSDN info, the high-order bit is set only on 95/98/ME.
13+
let is_nt = version < 0x8000_0000;
14+
15+
IS_NT = is_nt;
16+
SUPPORTS_ASYNC_IO = is_nt && c::CancelIo::option().is_some();
17+
18+
// at least 9x exports TryEnterCriticalSection, but it doesn't work, so we need to check the
19+
// version. MSDN specifies that the function is available on NT4 and later.
20+
SUPPORTS_TRY_ENTER_CRITICAL_SECTION = is_nt && major >= 4;
1121
};
1222
}
1323

@@ -22,3 +32,8 @@ pub fn is_windows_nt() -> bool {
2232
pub fn supports_async_io() -> bool {
2333
unsafe { SUPPORTS_ASYNC_IO }
2434
}
35+
36+
#[inline(always)]
37+
pub fn supports_try_enter_critical_section() -> bool {
38+
unsafe { SUPPORTS_TRY_ENTER_CRITICAL_SECTION }
39+
}

library/std/src/sys/windows/locks/mutex/compat.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::sys::c;
1+
use crate::sys::{c, compat};
22

33
#[derive(Debug, PartialEq)]
44
pub enum MutexKind {
@@ -15,7 +15,9 @@ pub static mut MUTEX_KIND: MutexKind = MutexKind::SrwLock;
1515
pub fn init() {
1616
let kind = if c::TryAcquireSRWLockExclusive::option().is_some() {
1717
MutexKind::SrwLock
18-
} else if c::TryEnterCriticalSection::option().is_some() {
18+
} else if compat::supports_try_enter_critical_section()
19+
&& c::TryEnterCriticalSection::option().is_some()
20+
{
1921
MutexKind::CriticalSection
2022
} else {
2123
MutexKind::Legacy

0 commit comments

Comments
 (0)