Skip to content

Channels

Channels are the primary way to communicate between concurrent tasks in Run. They allow one task to send a value and another to receive it.

ch := alloc(chan[int]) // unbuffered channel
ch := alloc(chan[int], 10) // buffered channel with capacity 10

Use <- to send and receive values.

package main
use "fmt"
fun producer(ch: chan int) {
for i in 0..5 {
ch <- i // send
}
}
pub fun main() {
ch := alloc(chan[int], 10)
run producer(ch)
for i in 0..5 {
val := <-ch // receive
fmt.println(val)
}
}

or range over a channel:

package main
use "fmt"
fun producer(ch: chan int) {
for i in 0..5 {
ch <- i // send
}
close(ch)
}
pub fun main() {
ch := alloc(chan[int], 10)
run producer(ch)
for val in ch {
fmt.println(val)
}
}

Use close(ch) to close a channel. This signals to the receiver that no more values will be sent.

ch := alloc(chan[int])
close(ch)

An unbuffered channel synchronizes the sender and receiver — the sender blocks until the receiver is ready, and vice versa. This makes unbuffered channels useful for direct handoffs between tasks.

A buffered channel allows sends to proceed without blocking until the buffer is full. This is useful when the sender and receiver run at different speeds.

ch := alloc(chan[string], 5)
ch <- "hello" // does not block (buffer has space)