1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

all: add builtin channel type chan elem_type (#6126)

This commit is contained in:
Uwe Krüger
2020-08-14 21:18:42 +02:00
committed by GitHub
parent 75212f9fab
commit 9602a25a0b
13 changed files with 279 additions and 6 deletions

View File

@@ -0,0 +1,36 @@
import sync
const (
num_iterations = 10000
)
struct St {
mut:
n int
}
// this function gets an array of channels for `St` references
fn do_rec_calc_send(chs []chan mut St) {
mut s := St{}
for {
if !(&sync.Channel(chs[0])).pop(&s) {
break
}
s.n++
(&sync.Channel(chs[1])).push(&s)
}
}
fn test_channel_array_mut() {
mut chs := [chan mut St{cap: 1}, chan mut St{}]
go do_rec_calc_send(chs)
mut t := St{
n: 100
}
for _ in 0 .. num_iterations {
(&sync.Channel(chs[0])).push(&t)
(&sync.Channel(chs[1])).pop(&t)
}
(&sync.Channel(chs[0])).close()
assert t.n == 100 + num_iterations
}

View File

@@ -0,0 +1,76 @@
import sync
fn do_rec_i64(ch chan i64) {
mut sum := i64(0)
for _ in 0 .. 300 {
mut a := i64(0)
(&sync.Channel(ch)).pop(&a)
sum += a
}
assert sum == 300 * (300 - 1) / 2
}
fn do_send_int(ch chan int) {
for i in 0 .. 300 {
(&sync.Channel(ch)).push(&i)
}
}
fn do_send_byte(ch chan byte) {
for i in 0 .. 300 {
ii := byte(i)
(&sync.Channel(ch)).push(&ii)
}
}
fn do_send_i64(mut ch sync.Channel) {
for i in 0 .. 300 {
ii := i64(i)
ch.push(&ii)
}
}
fn test_select() {
chi := chan int{}
mut chl := sync.new_channel<i64>(1)
chb := chan byte{cap: 10}
recch := chan i64{cap: 0}
go do_rec_i64(recch)
go do_send_int(chi)
go do_send_byte(chb)
go do_send_i64(mut chl)
mut channels := [&sync.Channel(chi), &sync.Channel(recch), chl, &sync.Channel(chb)]
directions := [sync.Direction.pop, .push, .pop, .pop]
mut sum := i64(0)
mut rl := i64(0)
mut ri := int(0)
mut rb := byte(0)
mut sl := i64(0)
mut objs := [voidptr(&ri), &sl, &rl, &rb]
for _ in 0 .. 1200 {
idx := sync.channel_select(mut channels, directions, mut objs, -1)
match idx {
0 {
sum += ri
}
1 {
sl++
}
2 {
sum += rl
}
3 {
sum += rb
}
else {
println('got $idx (timeout)')
}
}
}
// Use Gauß' formula for the first 2 contributions
expected_sum := 2 * (300 * (300 - 1) / 2) +
// the 3rd contribution is `byte` and must be seen modulo 256
256 * (256 - 1) / 2 +
44 * (44 - 1) / 2
assert sum == expected_sum
}

View File

@@ -111,6 +111,10 @@ pub:
pub fn new_channel<T>(n u32) &Channel {
st := sizeof(T)
return new_channel_st(n, st)
}
fn new_channel_st(n u32, st u32) &Channel {
return &Channel{
writesem: new_semaphore_init(if n > 0 { n + 1 } else { 1 })
readsem: new_semaphore_init(if n > 0 { u32(0) } else { 1 })