v2 / vlib / v / tests / concurrency / shared_lock_3_test.v
55 lines · 51 sloc · 1.0 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1import time
2
3struct St {
4mut:
5 a int
6}
7
8fn f(shared x St, shared z St) {
9 for _ in 0 .. reads_per_thread {
10 rlock x { // other instances may read at the same time
11 time.sleep(time.millisecond)
12 assert x.a == 7 || x.a == 5
13 }
14 }
15 lock z {
16 z.a--
17 }
18}
19
20const reads_per_thread = 30
21const read_threads = 10
22const writes = 5
23
24fn test_shared_lock() {
25 // object with separate read/write lock
26 shared x := &St{
27 a: 5
28 }
29 shared z := &St{
30 a: read_threads
31 }
32 for _ in 0 .. read_threads {
33 spawn f(shared x, shared z)
34 }
35 for i in 0 .. writes {
36 lock x { // wait for ongoing reads to finish, don't start new ones
37 x.a = 17 // this should never be read
38 time.sleep(50 * time.millisecond)
39 x.a = if (i & 1) == 0 { 7 } else { 5 }
40 } // now new reads are possible again
41 time.sleep(20 * time.millisecond)
42 }
43 // wait until all read threads are finished
44 for finished := false; true; {
45 mut rr := 0
46 rlock z {
47 rr = z.a
48 finished = z.a == 0
49 }
50 if finished {
51 break
52 }
53 time.sleep(100 * time.millisecond)
54 }
55}
56