v / vlib / sync / channel_polling_test.v
54 lines · 51 sloc · 1.2 KB · f09826e928f9612bab9299faefff7cf34a503362
Raw
1// Channel Benchmark
2//
3// `nobj` integers are sent thru a channel with queue length`buflen`
4// using `nsend` sender threads and `nrec` receiver threads.
5//
6// The receive threads add all received numbers and send them to the
7// main thread where the total sum is compare to the expected value.
8const nsend = 2
9const nrec = 2
10const buflen = 100
11const nobj = 10000
12const objs_per_thread = 5000
13
14fn do_rec(ch chan int, resch chan i64, n int) {
15 mut sum := i64(0)
16 for _ in 0 .. n {
17 mut r := 0
18 for ch.try_pop(mut r) != .success {
19 }
20 sum += r
21 }
22 println(sum)
23 resch <- sum
24}
25
26fn do_send(ch chan int, start int, end int) {
27 for i in start .. end {
28 for ch.try_push(i) != .success {
29 }
30 }
31}
32
33fn test_channel_polling() {
34 ch := chan int{cap: buflen}
35 resch := chan i64{}
36 for _ in 0 .. nrec {
37 spawn do_rec(ch, resch, objs_per_thread)
38 }
39 mut n := nobj
40 for _ in 0 .. nsend {
41 end := n
42 n -= objs_per_thread
43 spawn do_send(ch, n, end)
44 }
45 mut sum := i64(0)
46 for _ in 0 .. nrec {
47 sum += <-resch
48 println('> running sum: ${sum}')
49 }
50 // use sum formula by Gauß to calculate the expected result
51 expected_sum := i64(nobj) * (nobj - 1) / 2
52 println('expected sum: ${expected_sum} | sum: ${sum}')
53 assert sum == expected_sum
54}
55