v / vlib / sync
Raw file | 65 loc (56 sloc) | 871 bytes | Latest commit hash 017ace6ea
1const n = 1000
2
3const c = 100
4
5fn f(ch chan int) {
6 for _ in 0 .. n {
7 _ := <-ch
8 }
9 ch.close()
10}
11
12fn test_push_or_unbuffered() {
13 ch := chan int{}
14 spawn f(ch)
15 mut j := 0
16 for {
17 ch <- j or { break }
18
19 j++
20 }
21 assert j == n
22}
23
24fn test_push_or_buffered() {
25 ch := chan int{cap: c}
26 spawn f(ch)
27 mut j := 0
28 for {
29 ch <- j or { break }
30
31 j++
32 }
33 // we don't know how many elements are in the buffer when the channel
34 // is closed, so check j against an interval
35 assert j >= n
36 assert j <= n + c
37}
38
39fn g(ch chan int, res chan int) {
40 mut j := 0
41 for {
42 ch <- j or { break }
43
44 j++
45 }
46 println('done ${j}')
47 res <- j
48}
49
50fn test_many_senders() {
51 ch := chan int{}
52 res := chan int{}
53 spawn g(ch, res)
54 spawn g(ch, res)
55 spawn g(ch, res)
56 mut k := 0
57 for _ in 0 .. 3 * n {
58 k = <-ch
59 }
60 ch.close()
61 mut sum := <-res
62 sum += <-res
63 sum += <-res
64 assert sum == 3 * n
65}