v2 / vlib / v / tests / concurrency / shared_lock_6_test.v
59 lines · 56 sloc · 932 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1struct St {
2mut:
3 a int
4}
5
6fn (shared x St) f(shared y St, shared z St) {
7 for _ in 0 .. 10000 {
8 lock x; rlock y, z {
9 x.a = y.a + z.a
10 if x.a > 1000000 {
11 x.a /= 2
12 }
13 }
14 }
15}
16
17fn (shared x St) g(shared y St, shared z St) {
18 for _ in 0 .. 10000 {
19 lock y, z; rlock x {
20 y.a += x.a
21 if y.a > 1000000 {
22 y.a /= 2
23 }
24 z.a += x.a
25 if z.a > 1000000 {
26 z.a /= 2
27 }
28 }
29 }
30}
31
32fn test_shared_receiver_lock() {
33 shared x := St{
34 a: 5
35 }
36 shared y := St{
37 a: 7
38 }
39 shared z := St{
40 a: 103
41 }
42 t1 := spawn x.f(shared y, shared x)
43 t2 := spawn y.f(shared y, shared z)
44 t3 := spawn z.g(shared x, shared z)
45 t4 := spawn x.g(shared x, shared x)
46 t5 := spawn z.f(shared z, shared z)
47 t1.wait()
48 t2.wait()
49 t3.wait()
50 t4.wait()
51 t5.wait()
52 // the result is unpredictable - but should be positive
53 rlock x, y, z {
54 assert x.a > 10000
55 assert y.a > 10000
56 assert z.a > 10000
57 println('${x.a} ${y.a} ${z.a}')
58 }
59}
60