v / vlib / sync / mutex_test.v
42 lines · 38 sloc · 767 bytes · da3112e5453b553ca230d47590e0d3ed6be6478d
Raw
1import sync
2
3struct Counter {
4pub mut:
5 i int
6}
7
8fn write_10000(mut co Counter, mut mx sync.Mutex) {
9 mx.lock()
10 co.i = 10000
11 mx.unlock()
12}
13
14fn test_mutex() {
15 mut co := &Counter{10086}
16 mut mx := sync.new_mutex()
17 mx.lock()
18 co.i = 888
19 th := spawn write_10000(mut co, mut mx)
20 mx.unlock() // after mx unlock, thread write_10000 can continue
21 th.wait()
22 mx.destroy()
23 assert co.i == 10000
24}
25
26fn test_try_lock_mutex() {
27 // In Windows, try_lock only avalible after Windows 7
28 $if windows {
29 $if !windows_7 ? {
30 return
31 }
32 }
33 mut mx := sync.new_mutex()
34 mx.lock()
35 try_fail := mx.try_lock()
36 assert try_fail == false
37 mx.unlock()
38 try_success := mx.try_lock()
39 assert try_success == true
40 mx.unlock() // you must unlock it, after try_lock success
41 mx.destroy()
42}
43