mirror of
https://github.com/vlang/v.git
synced 2025-09-14 06:52:36 +03:00
sync: add .try_lock() to mutex/rwmutex, add tests (#20381)
This commit is contained in:
parent
4e5c597569
commit
d7fc66f054
5 changed files with 203 additions and 0 deletions
42
vlib/sync/mutex_test.v
Normal file
42
vlib/sync/mutex_test.v
Normal 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()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue