sync: add .try_lock() to mutex/rwmutex, add tests (#20381)

This commit is contained in:
kbkpbot 2024-01-05 21:57:04 +08:00 committed by GitHub
parent 4e5c597569
commit d7fc66f054
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 203 additions and 0 deletions

View file

@ -76,6 +76,19 @@ pub fn (mut m Mutex) @lock() {
C.AcquireSRWLockExclusive(&m.mx)
}
// try_lock try to lock the mutex instance and return immediately.
// If the mutex was already locked, it will return false.
// NOTE: try_lock require Windows 7 or later. Before Windows 7, it will always return false.
// NOTE: To enable try_lock , you should compile your project with `-d windows_7`, like `v . -d windows_7`
// https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-tryacquiresrwlockexclusive
pub fn (mut m Mutex) try_lock() bool {
$if windows_7 ? {
return C.TryAcquireSRWLockExclusive(&m.mx) != 0
} $else {
return false
}
}
pub fn (mut m Mutex) unlock() {
C.ReleaseSRWLockExclusive(&m.mx)
}
@ -89,6 +102,32 @@ pub fn (mut m RwMutex) @lock() {
C.AcquireSRWLockExclusive(&m.mx)
}
// try_rlock try to lock the given RwMutex instance for reading and return immediately.
// If the mutex was already locked, it will return false.
// NOTE: try_rlock require Windows 7 or later. Before Windows 7, it will always return false.
// NOTE: To enable try_rlock , you should compile your project with `-d windows_7`, like `v . -d windows_7`
// https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-tryacquiresrwlockshared
pub fn (mut m RwMutex) try_rlock() bool {
$if windows_7 ? {
return C.TryAcquireSRWLockShared(&m.mx) != 0
} $else {
return false
}
}
// try_wlock try to lock the given RwMutex instance for writing and return immediately.
// If the mutex was already locked, it will return false.
// NOTE: try_wlock require Windows 7 or later. Before Windows 7, it will always return false.
// NOTE: To enable try_wlock , you should compile your project with `-d windows_7`, like `v . -d windows_7`
// https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-tryacquiresrwlockexclusive
pub fn (mut m RwMutex) try_wlock() bool {
$if windows_7 ? {
return C.TryAcquireSRWLockExclusive(&m.mx) != 0
} $else {
return false
}
}
// Windows SRWLocks have different function to unlock
// So provide two functions here, too, to have a common interface
pub fn (mut m RwMutex) runlock() {