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

42
vlib/sync/mutex_test.v Normal file
View file

@ -0,0 +1,42 @@
import sync
struct Counter {
pub mut:
i int
}
fn write_10000(mut co Counter, mut mx sync.Mutex) {
mx.@lock()
co.i = 10000
mx.unlock()
}
fn test_mutex() {
mut co := &Counter{10086}
mut mx := sync.new_mutex()
mx.@lock()
co.i = 888
th := spawn write_10000(mut co, mut mx)
mx.unlock() // after mx unlock, thread write_10000 can continue
th.wait()
mx.destroy()
assert co.i == 10000
}
fn test_try_lock_mutex() {
// In Windows, try_lock only avalible after Windows 7
$if windows {
$if !windows_7 ? {
return
}
}
mut mx := sync.new_mutex()
mx.@lock()
try_fail := mx.try_lock()
assert try_fail == false
mx.unlock()
try_sucess := mx.try_lock()
assert try_sucess == true
mx.unlock() // you must unlock it, after try_lock sucess
mx.destroy()
}