2021-01-06 23:19:40 +03:00
|
|
|
const n = 1000
|
2021-05-08 13:32:29 +03:00
|
|
|
|
2021-01-06 23:19:40 +03:00
|
|
|
const c = 100
|
|
|
|
|
|
|
|
fn f(ch chan int) {
|
|
|
|
for _ in 0 .. n {
|
|
|
|
_ := <-ch
|
|
|
|
}
|
|
|
|
ch.close()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_push_or_unbuffered() {
|
|
|
|
ch := chan int{}
|
2022-11-05 10:46:40 +03:00
|
|
|
spawn f(ch)
|
2021-01-06 23:19:40 +03:00
|
|
|
mut j := 0
|
|
|
|
for {
|
2021-05-08 13:32:29 +03:00
|
|
|
ch <- j or { break }
|
|
|
|
|
2021-01-06 23:19:40 +03:00
|
|
|
j++
|
|
|
|
}
|
|
|
|
assert j == n
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_push_or_buffered() {
|
|
|
|
ch := chan int{cap: c}
|
2022-11-05 10:46:40 +03:00
|
|
|
spawn f(ch)
|
2021-01-06 23:19:40 +03:00
|
|
|
mut j := 0
|
|
|
|
for {
|
2021-05-08 13:32:29 +03:00
|
|
|
ch <- j or { break }
|
|
|
|
|
2021-01-06 23:19:40 +03:00
|
|
|
j++
|
|
|
|
}
|
|
|
|
// we don't know how many elements are in the buffer when the channel
|
|
|
|
// is closed, so check j against an interval
|
|
|
|
assert j >= n
|
|
|
|
assert j <= n + c
|
|
|
|
}
|
|
|
|
|
|
|
|
fn g(ch chan int, res chan int) {
|
|
|
|
mut j := 0
|
|
|
|
for {
|
2021-05-08 13:32:29 +03:00
|
|
|
ch <- j or { break }
|
|
|
|
|
2021-01-06 23:19:40 +03:00
|
|
|
j++
|
|
|
|
}
|
|
|
|
println('done $j')
|
|
|
|
res <- j
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_many_senders() {
|
|
|
|
ch := chan int{}
|
|
|
|
res := chan int{}
|
2022-11-05 10:46:40 +03:00
|
|
|
spawn g(ch, res)
|
|
|
|
spawn g(ch, res)
|
|
|
|
spawn g(ch, res)
|
2021-01-06 23:19:40 +03:00
|
|
|
mut k := 0
|
|
|
|
for _ in 0 .. 3 * n {
|
|
|
|
k = <-ch
|
|
|
|
}
|
|
|
|
ch.close()
|
|
|
|
mut sum := <-res
|
|
|
|
sum += <-res
|
|
|
|
sum += <-res
|
|
|
|
assert sum == 3 * n
|
|
|
|
}
|