v / vlib / sync
Raw file | 62 loc (57 sloc) | 1.07 KB | Latest commit hash e81e0ac70
1import time
2
3fn do_rec_i64(ch chan i64) {
4 mut sum := i64(0)
5 for _ in 0 .. 300 {
6 sum += <-ch
7 }
8 assert sum == 300 * (300 - 1) / 2
9}
10
11fn do_send_int(ch chan int) {
12 for i in 0 .. 300 {
13 ch <- i
14 }
15}
16
17fn do_send_u8(ch chan u8) {
18 for i in 0 .. 300 {
19 ch <- u8(i)
20 }
21}
22
23fn do_send_i64(ch chan i64) {
24 for i in 0 .. 300 {
25 ch <- i
26 }
27}
28
29fn test_select() {
30 chi := chan int{}
31 chl := chan i64{cap: 1}
32 chb := chan u8{cap: 10}
33 recch := chan i64{cap: 0}
34 spawn do_rec_i64(recch)
35 spawn do_send_int(chi)
36 spawn do_send_u8(chb)
37 spawn do_send_i64(chl)
38 mut sum := i64(0)
39 mut rl := i64(0)
40 mut sl := i64(0)
41 for _ in 0 .. 1200 {
42 select {
43 ri := <-chi {
44 sum += ri
45 }
46 recch <- sl {
47 sl++
48 }
49 rl = <-chl {
50 sum += rl
51 }
52 rb := <-chb {
53 sum += rb
54 }
55 }
56 }
57 // Use Gauß' formula for the first 2 contributions
58 // the 3rd contribution is `byte` and must be seen modulo 256
59 expected_sum := 2 * (300 * (300 - 1) / 2) + 256 * (256 - 1) / 2 + 44 * (44 - 1) / 2
60 assert sum == expected_sum
61 time.sleep(20 * time.millisecond) // to give assert in coroutine enough time
62}