2020-08-18 00:35:36 +03:00
|
|
|
import time
|
2020-08-14 22:18:42 +03:00
|
|
|
|
|
|
|
fn do_rec_i64(ch chan i64) {
|
|
|
|
mut sum := i64(0)
|
|
|
|
for _ in 0 .. 300 {
|
2020-08-18 00:35:36 +03:00
|
|
|
sum += <-ch
|
2020-08-14 22:18:42 +03:00
|
|
|
}
|
|
|
|
assert sum == 300 * (300 - 1) / 2
|
|
|
|
}
|
|
|
|
|
|
|
|
fn do_send_int(ch chan int) {
|
|
|
|
for i in 0 .. 300 {
|
2020-08-18 00:35:36 +03:00
|
|
|
ch <- i
|
2020-08-14 22:18:42 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-15 18:25:45 +03:00
|
|
|
fn do_send_u8(ch chan u8) {
|
2020-08-14 22:18:42 +03:00
|
|
|
for i in 0 .. 300 {
|
2022-04-15 14:58:56 +03:00
|
|
|
ch <- u8(i)
|
2020-08-14 22:18:42 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-18 00:35:36 +03:00
|
|
|
fn do_send_i64(ch chan i64) {
|
2020-08-14 22:18:42 +03:00
|
|
|
for i in 0 .. 300 {
|
2020-08-18 00:35:36 +03:00
|
|
|
ch <- i
|
2020-08-14 22:18:42 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_select() {
|
|
|
|
chi := chan int{}
|
2020-08-18 00:35:36 +03:00
|
|
|
chl := chan i64{cap: 1}
|
2022-04-15 18:25:45 +03:00
|
|
|
chb := chan u8{cap: 10}
|
2020-08-14 22:18:42 +03:00
|
|
|
recch := chan i64{cap: 0}
|
2022-11-05 10:46:40 +03:00
|
|
|
spawn do_rec_i64(recch)
|
|
|
|
spawn do_send_int(chi)
|
|
|
|
spawn do_send_u8(chb)
|
|
|
|
spawn do_send_i64(chl)
|
2020-08-14 22:18:42 +03:00
|
|
|
mut sum := i64(0)
|
|
|
|
mut rl := i64(0)
|
|
|
|
mut sl := i64(0)
|
|
|
|
for _ in 0 .. 1200 {
|
2020-09-20 04:50:09 +03:00
|
|
|
select {
|
|
|
|
ri := <-chi {
|
2020-08-14 22:18:42 +03:00
|
|
|
sum += ri
|
|
|
|
}
|
2020-09-20 04:50:09 +03:00
|
|
|
recch <- sl {
|
2020-08-14 22:18:42 +03:00
|
|
|
sl++
|
|
|
|
}
|
2020-09-20 04:50:09 +03:00
|
|
|
rl = <-chl {
|
2020-08-14 22:18:42 +03:00
|
|
|
sum += rl
|
|
|
|
}
|
2020-09-20 04:50:09 +03:00
|
|
|
rb := <-chb {
|
2020-08-14 22:18:42 +03:00
|
|
|
sum += rb
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Use Gauß' formula for the first 2 contributions
|
2020-10-14 22:51:16 +03:00
|
|
|
// the 3rd contribution is `byte` and must be seen modulo 256
|
2021-02-21 18:05:03 +03:00
|
|
|
expected_sum := 2 * (300 * (300 - 1) / 2) + 256 * (256 - 1) / 2 + 44 * (44 - 1) / 2
|
2020-08-14 22:18:42 +03:00
|
|
|
assert sum == expected_sum
|
2021-02-27 20:41:06 +03:00
|
|
|
time.sleep(20 * time.millisecond) // to give assert in coroutine enough time
|
2020-08-14 22:18:42 +03:00
|
|
|
}
|