2020-09-05 02:36:20 +03:00
|
|
|
// Channel Benchmark
|
|
|
|
//
|
|
|
|
// `nobj` integers are sent thru a channel with queue length`buflen`
|
|
|
|
// using `nsend` sender threads and `nrec` receiver threads.
|
|
|
|
//
|
|
|
|
// The receive threads add all received numbers and send them to the
|
|
|
|
// main thread where the total sum is compare to the expected value.
|
|
|
|
const (
|
2020-10-26 15:41:57 +03:00
|
|
|
nsend = 2
|
|
|
|
nrec = 2
|
|
|
|
buflen = 100
|
|
|
|
nobj = 10000
|
2020-09-05 02:36:20 +03:00
|
|
|
objs_per_thread = 5000
|
|
|
|
)
|
|
|
|
|
|
|
|
fn do_rec(ch chan int, resch chan i64, n int) {
|
|
|
|
mut sum := i64(0)
|
|
|
|
for _ in 0 .. n {
|
|
|
|
mut r := 0
|
2021-04-19 11:41:21 +03:00
|
|
|
for ch.try_pop(mut r) != .success {
|
2020-10-26 15:41:57 +03:00
|
|
|
}
|
2020-09-05 02:36:20 +03:00
|
|
|
sum += r
|
|
|
|
}
|
|
|
|
println(sum)
|
|
|
|
resch <- sum
|
|
|
|
}
|
|
|
|
|
2020-10-26 15:41:57 +03:00
|
|
|
fn do_send(ch chan int, start int, end int) {
|
2020-09-05 02:36:20 +03:00
|
|
|
for i in start .. end {
|
2020-10-26 15:41:57 +03:00
|
|
|
for ch.try_push(i) != .success {
|
|
|
|
}
|
2020-09-05 02:36:20 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_channel_polling() {
|
|
|
|
ch := chan int{cap: buflen}
|
|
|
|
resch := chan i64{}
|
2020-09-27 11:18:55 +03:00
|
|
|
for _ in 0 .. nrec {
|
2022-11-05 10:46:40 +03:00
|
|
|
spawn do_rec(ch, resch, objs_per_thread)
|
2020-09-05 02:36:20 +03:00
|
|
|
}
|
|
|
|
mut n := nobj
|
2020-09-27 11:18:55 +03:00
|
|
|
for _ in 0 .. nsend {
|
2020-09-05 02:36:20 +03:00
|
|
|
end := n
|
|
|
|
n -= objs_per_thread
|
2022-11-05 10:46:40 +03:00
|
|
|
spawn do_send(ch, n, end)
|
2020-09-05 02:36:20 +03:00
|
|
|
}
|
|
|
|
mut sum := i64(0)
|
|
|
|
for _ in 0 .. nrec {
|
|
|
|
sum += <-resch
|
2022-11-15 16:53:13 +03:00
|
|
|
println('> running sum: ${sum}')
|
2020-09-05 02:36:20 +03:00
|
|
|
}
|
|
|
|
// use sum formula by Gauß to calculate the expected result
|
2020-10-26 15:41:57 +03:00
|
|
|
expected_sum := i64(nobj) * (nobj - 1) / 2
|
2022-11-15 16:53:13 +03:00
|
|
|
println('expected sum: ${expected_sum} | sum: ${sum}')
|
2020-09-05 02:36:20 +03:00
|
|
|
assert sum == expected_sum
|
|
|
|
}
|