v2 / vlib / v / fmt / tests / shared_input.vv
83 lines · 76 sloc · 1.34 KB · 3ac63cce869c5a0d7ee093864484344ad44474e1
Raw
1import sync
2import time
3
4struct St {
5mut:
6 a int
7}
8
9fn (shared x St) f(shared z St) {
10 for _ in 0 .. reads_per_thread {
11 rlock x { // other instances may read at the same time
12 time.sleep(time.millisecond)
13 assert x.a == 7 || x.a == 5
14 }
15 }
16 lock z {
17 z.a--
18 }
19}
20
21fn g() shared St {
22shared x := St{a: 12 }
23 return x
24}
25
26fn h() ?shared St {
27 return error('no value')
28}
29
30fn k() {
31 shared x := g()
32 shared y := h() or {
33 shared f := St{}
34 f
35 }
36 shared z := h()?
37 shared p := v
38 v := rlock z { z.a }
39 rlock x; lock y, z; rlock p {
40 z.a = x.a + y.a
41 }
42 println(v)
43}
44
45const (
46 reads_per_thread = 30
47 read_threads = 10
48 writes = 5
49)
50
51fn test_shared_lock() {
52 // object with separate read/write lock
53shared x := &St {
54a: 5
55}
56 shared z :=
57&St{
58 a: read_threads
59 }
60 for _ in 0.. read_threads {
61 spawn x.f(shared z)
62 }
63 for i in 0..writes {
64 lock x { // wait for ongoing reads to finish, don't start new ones
65 x.a = 17 // this value should never be read
66 time.sleep(50* time.millisecond)
67 x.a = if (i & 1) == 0 { 7 } else { 5 }
68 } // now new reads are possible again
69time.sleep(20*time.millisecond)
70 }
71 // wait until all read threads are finished
72for finished:=false;; {
73 mut rr := 0
74 rlock z {
75 rr = z.a
76 finished = z.a == 0
77}
78if finished {
79 break
80 }
81 time.sleep(100*time.millisecond)
82 }
83}
84