2021-04-22 07:07:56 +03:00
|
|
|
module sync
|
|
|
|
|
2020-08-10 19:06:42 +03:00
|
|
|
import time
|
2020-08-10 07:22:20 +03:00
|
|
|
|
2021-04-22 07:07:56 +03:00
|
|
|
fn do_rec_i64(mut ch Channel) {
|
2020-08-10 07:22:20 +03:00
|
|
|
mut sum := i64(0)
|
|
|
|
for i in 0 .. 300 {
|
|
|
|
if i == 200 {
|
|
|
|
ch.close()
|
|
|
|
}
|
|
|
|
mut a := i64(0)
|
|
|
|
if ch.pop(&a) {
|
|
|
|
sum += a
|
|
|
|
}
|
|
|
|
}
|
|
|
|
assert sum == 200 * (200 - 1) / 2
|
|
|
|
}
|
|
|
|
|
2021-04-22 07:07:56 +03:00
|
|
|
fn do_send_int(mut ch Channel) {
|
2020-08-10 07:22:20 +03:00
|
|
|
for i in 0 .. 300 {
|
|
|
|
ch.push(&i)
|
|
|
|
}
|
|
|
|
ch.close()
|
|
|
|
}
|
|
|
|
|
2022-04-15 14:58:56 +03:00
|
|
|
fn do_send_u8(mut ch Channel) {
|
2020-08-10 07:22:20 +03:00
|
|
|
for i in 0 .. 300 {
|
2022-04-15 14:58:56 +03:00
|
|
|
ii := u8(i)
|
2020-08-10 07:22:20 +03:00
|
|
|
ch.push(&ii)
|
|
|
|
}
|
|
|
|
ch.close()
|
|
|
|
}
|
|
|
|
|
2021-04-22 07:07:56 +03:00
|
|
|
fn do_send_i64(mut ch Channel) {
|
2020-08-10 07:22:20 +03:00
|
|
|
for i in 0 .. 300 {
|
|
|
|
ii := i64(i)
|
|
|
|
ch.push(&ii)
|
|
|
|
}
|
|
|
|
ch.close()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_select() {
|
2022-11-26 19:23:26 +03:00
|
|
|
mut chi := new_channel[int](0)
|
|
|
|
mut chl := new_channel[i64](1)
|
|
|
|
mut chb := new_channel[u8](10)
|
|
|
|
mut recch := new_channel[i64](0)
|
2022-11-05 10:46:40 +03:00
|
|
|
spawn do_rec_i64(mut recch)
|
|
|
|
spawn do_send_int(mut chi)
|
|
|
|
spawn do_send_u8(mut chb)
|
|
|
|
spawn do_send_i64(mut chl)
|
2020-08-10 07:22:20 +03:00
|
|
|
mut channels := [chi, recch, chl, chb]
|
2021-04-22 07:07:56 +03:00
|
|
|
directions := [Direction.pop, .push, .pop, .pop]
|
2020-08-10 07:22:20 +03:00
|
|
|
mut sum := i64(0)
|
|
|
|
mut rl := i64(0)
|
|
|
|
mut ri := int(0)
|
2022-04-15 14:58:56 +03:00
|
|
|
mut rb := u8(0)
|
2020-08-10 07:22:20 +03:00
|
|
|
mut sl := i64(0)
|
|
|
|
mut objs := [voidptr(&ri), &sl, &rl, &rb]
|
|
|
|
for j in 0 .. 1101 {
|
2021-04-22 07:07:56 +03:00
|
|
|
idx := channel_select(mut channels, directions, mut objs, time.infinite)
|
2020-08-10 07:22:20 +03:00
|
|
|
match idx {
|
|
|
|
0 {
|
|
|
|
sum += ri
|
|
|
|
}
|
|
|
|
1 {
|
|
|
|
sl++
|
|
|
|
}
|
|
|
|
2 {
|
|
|
|
sum += rl
|
|
|
|
}
|
|
|
|
3 {
|
|
|
|
sum += rb
|
|
|
|
}
|
|
|
|
-2 {
|
|
|
|
// channel was closed - last item
|
|
|
|
assert j == 1100
|
|
|
|
}
|
|
|
|
else {
|
2022-11-15 16:53:13 +03:00
|
|
|
println('got ${idx} (timeout)')
|
2020-08-10 07:22:20 +03:00
|
|
|
assert false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if j == 1100 {
|
|
|
|
// check also in other direction
|
|
|
|
assert idx == -2
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// 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-05-08 13:32:29 +03:00
|
|
|
expected_sum := 2 * (300 * (300 - 1) / 2) + 256 * (256 - 1) / 2 + 44 * (44 - 1) / 2
|
2020-08-10 07:22:20 +03:00
|
|
|
assert sum == expected_sum
|
|
|
|
}
|