2020-08-10 06:22:20 +02:00
|
|
|
import sync
|
|
|
|
|
2021-01-22 08:37:29 +01:00
|
|
|
fn do_rec(ch chan int, resch chan i64) {
|
2020-08-10 06:22:20 +02:00
|
|
|
mut sum := i64(0)
|
2020-10-26 13:41:57 +01:00
|
|
|
for {
|
2021-01-22 08:37:29 +01:00
|
|
|
a := <-ch or {
|
2020-08-10 06:22:20 +02:00
|
|
|
break
|
|
|
|
}
|
|
|
|
sum += a
|
|
|
|
}
|
2021-01-22 08:37:29 +01:00
|
|
|
assert ch.closed == true
|
2020-08-10 06:22:20 +02:00
|
|
|
println(sum)
|
2021-01-22 08:37:29 +01:00
|
|
|
resch <- sum
|
2020-08-10 06:22:20 +02:00
|
|
|
}
|
|
|
|
|
2021-01-22 08:37:29 +01:00
|
|
|
fn do_send(ch chan int) {
|
2020-08-10 06:22:20 +02:00
|
|
|
for i in 0 .. 8000 {
|
2021-01-22 08:37:29 +01:00
|
|
|
ch <- i
|
2020-08-10 06:22:20 +02:00
|
|
|
}
|
2021-01-22 08:37:29 +01:00
|
|
|
assert ch.closed == false
|
2020-08-10 06:22:20 +02:00
|
|
|
ch.close()
|
2021-01-22 08:37:29 +01:00
|
|
|
assert ch.closed == true
|
2020-08-10 06:22:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn test_channel_close_buffered_multi() {
|
2021-01-22 08:37:29 +01:00
|
|
|
ch := chan int{cap: 10}
|
|
|
|
resch := chan i64{}
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_send(ch)
|
2020-08-10 06:22:20 +02:00
|
|
|
mut sum := i64(0)
|
|
|
|
for _ in 0 .. 4 {
|
2021-01-22 08:37:29 +01:00
|
|
|
sum += <- resch
|
2020-08-10 06:22:20 +02:00
|
|
|
}
|
|
|
|
assert sum == i64(8000) * (8000 - 1) / 2
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_channel_close_unbuffered_multi() {
|
2021-01-22 08:37:29 +01:00
|
|
|
ch := chan int{}
|
|
|
|
resch := chan i64{}
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_send(ch)
|
2020-08-10 06:22:20 +02:00
|
|
|
mut sum := i64(0)
|
|
|
|
for _ in 0 .. 4 {
|
2021-01-22 08:37:29 +01:00
|
|
|
sum += <-resch
|
2020-08-10 06:22:20 +02:00
|
|
|
}
|
|
|
|
assert sum == i64(8000) * (8000 - 1) / 2
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_channel_close_buffered() {
|
2021-01-22 08:37:29 +01:00
|
|
|
ch := chan int{cap: 100}
|
|
|
|
resch := chan i64{}
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_send(ch)
|
2020-08-10 06:22:20 +02:00
|
|
|
mut sum := i64(0)
|
2021-01-22 08:37:29 +01:00
|
|
|
sum += <-resch
|
2020-08-10 06:22:20 +02:00
|
|
|
assert sum == i64(8000) * (8000 - 1) / 2
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_channel_close_unbuffered() {
|
2021-01-22 08:37:29 +01:00
|
|
|
ch := chan int{}
|
|
|
|
resch := chan i64{cap: 100}
|
|
|
|
go do_rec(ch, resch)
|
|
|
|
go do_send(ch)
|
2020-08-10 06:22:20 +02:00
|
|
|
mut sum := i64(0)
|
2021-01-22 08:37:29 +01:00
|
|
|
sum += <-resch
|
2020-08-10 06:22:20 +02:00
|
|
|
assert sum == i64(8000) * (8000 - 1) / 2
|
|
|
|
}
|