v2 / vlib / v / tests / concurrency / shared_array_test.v
74 lines · 70 sloc · 1.21 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1import time
2
3fn incr(shared foo []int, index int) {
4 for _ in 0 .. 100000 {
5 lock foo {
6 foo[index] = foo[index] + 1
7 }
8 }
9 lock foo {
10 foo[2]++
11 }
12}
13
14fn test_shared_array() {
15 shared foo := &[10, 20, 0]
16 spawn incr(shared foo, 0)
17 spawn incr(shared foo, 1)
18 spawn incr(shared foo, 0)
19 spawn incr(shared foo, 1)
20 for _ in 0 .. 50000 {
21 lock foo {
22 foo[0] -= 2
23 foo[1] += 3
24 }
25 }
26 mut finished_threads := 0
27 for {
28 rlock foo {
29 finished_threads = foo[2]
30 }
31 if finished_threads == 4 {
32 break
33 }
34 time.sleep(100 * time.millisecond)
35 }
36 rlock foo {
37 f0 := foo[0]
38 f1 := foo[1]
39 assert f0 == 100010
40 assert f1 == 350020
41 }
42}
43
44fn test_shared_init_syntax() {
45 shared foo := &[3, 5, 6, -12]
46 shared bar := [-12.5, 23.125, 6.0625, 12.5]
47 shared baz := &[]int{len: 5, cap: 12}
48 shared qux := []f64{len: 7}
49 shared quux := new_array()
50 lock foo {
51 foo[2] = 20
52 }
53 lock bar {
54 bar[3] = 12.5
55 }
56 lock baz, qux, quux {
57 baz[3] = 12
58 qux[6] = -17.0625
59 quux[2] = 7.0625
60 }
61 rlock foo, bar, baz, qux, quux {
62 assert foo[2] == 20
63 assert bar[3] == 12.5
64 assert baz[3] == 12
65 assert qux[6] == -17.0625
66 assert quux[1] == 6.25
67 assert quux[2] == 7.0625
68 }
69}
70
71fn new_array() []f64 {
72 a := [12.5, 6.25, -3.125, 1.75]
73 return a
74}
75