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. |
8 | const ( |
9 | nsend = 2 |
10 | nrec = 2 |
11 | buflen = 100 |
12 | nobj = 10000 |
13 | objs_per_thread = 5000 |
14 | ) |
15 | |
16 | fn do_rec(ch chan int, resch chan i64, n int) { |
17 | mut sum := i64(0) |
18 | for _ in 0 .. n { |
19 | mut r := 0 |
20 | for ch.try_pop(mut r) != .success { |
21 | } |
22 | sum += r |
23 | } |
24 | println(sum) |
25 | resch <- sum |
26 | } |
27 | |
28 | fn do_send(ch chan int, start int, end int) { |
29 | for i in start .. end { |
30 | for ch.try_push(i) != .success { |
31 | } |
32 | } |
33 | } |
34 | |
35 | fn test_channel_polling() { |
36 | ch := chan int{cap: buflen} |
37 | resch := chan i64{} |
38 | for _ in 0 .. nrec { |
39 | spawn do_rec(ch, resch, objs_per_thread) |
40 | } |
41 | mut n := nobj |
42 | for _ in 0 .. nsend { |
43 | end := n |
44 | n -= objs_per_thread |
45 | spawn do_send(ch, n, end) |
46 | } |
47 | mut sum := i64(0) |
48 | for _ in 0 .. nrec { |
49 | sum += <-resch |
50 | println('> running sum: ${sum}') |
51 | } |
52 | // use sum formula by Gauß to calculate the expected result |
53 | expected_sum := i64(nobj) * (nobj - 1) / 2 |
54 | println('expected sum: ${expected_sum} | sum: ${sum}') |
55 | assert sum == expected_sum |
56 | } |