v / vlib / sync
Raw file | 92 loc (86 sloc) | 1.62 KB | Latest commit hash ef5be22f8
1module sync
2
3import time
4
5fn do_rec_i64(mut ch Channel) {
6 mut sum := i64(0)
7 for i in 0 .. 300 {
8 if i == 200 {
9 ch.close()
10 }
11 mut a := i64(0)
12 if ch.pop(&a) {
13 sum += a
14 }
15 }
16 assert sum == 200 * (200 - 1) / 2
17}
18
19fn do_send_int(mut ch Channel) {
20 for i in 0 .. 300 {
21 ch.push(&i)
22 }
23 ch.close()
24}
25
26fn do_send_u8(mut ch Channel) {
27 for i in 0 .. 300 {
28 ii := u8(i)
29 ch.push(&ii)
30 }
31 ch.close()
32}
33
34fn do_send_i64(mut ch Channel) {
35 for i in 0 .. 300 {
36 ii := i64(i)
37 ch.push(&ii)
38 }
39 ch.close()
40}
41
42fn test_select() {
43 mut chi := new_channel[int](0)
44 mut chl := new_channel[i64](1)
45 mut chb := new_channel[u8](10)
46 mut recch := new_channel[i64](0)
47 spawn do_rec_i64(mut recch)
48 spawn do_send_int(mut chi)
49 spawn do_send_u8(mut chb)
50 spawn do_send_i64(mut chl)
51 mut channels := [chi, recch, chl, chb]
52 directions := [Direction.pop, .push, .pop, .pop]
53 mut sum := i64(0)
54 mut rl := i64(0)
55 mut ri := int(0)
56 mut rb := u8(0)
57 mut sl := i64(0)
58 mut objs := [voidptr(&ri), &sl, &rl, &rb]
59 for j in 0 .. 1101 {
60 idx := channel_select(mut channels, directions, mut objs, time.infinite)
61 match idx {
62 0 {
63 sum += ri
64 }
65 1 {
66 sl++
67 }
68 2 {
69 sum += rl
70 }
71 3 {
72 sum += rb
73 }
74 -2 {
75 // channel was closed - last item
76 assert j == 1100
77 }
78 else {
79 println('got ${idx} (timeout)')
80 assert false
81 }
82 }
83 if j == 1100 {
84 // check also in other direction
85 assert idx == -2
86 }
87 }
88 // Use Gauß' formula for the first 2 contributions
89 // the 3rd contribution is `byte` and must be seen modulo 256
90 expected_sum := 2 * (300 * (300 - 1) / 2) + 256 * (256 - 1) / 2 + 44 * (44 - 1) / 2
91 assert sum == expected_sum
92}