Channel Patterns
Channels are the primary message-passing mechanism in Nyx. channel_new(capacity) creates a buffered channel, channel_send pushes a value, and channel_recv blocks until a value is available. Channels are declared as Map type.
Code
// Channels — typed message passing between threads
// Canales — paso de mensajes tipado entre hilos
var ch: Map = Map.new()
fn producer() -> int {
var i: int = 0
while i < 5 {
channel_send(ch, i)
i = i + 1
}
// Send sentinel to signal done
channel_send(ch, -1)
return 0
}
fn main() -> int {
// Create a buffered channel (capacity 10)
ch = channel_new(10)
// Spawn producer thread
let h: int = thread_spawn(producer)
// Receive messages until sentinel
var running: bool = true
while running {
let val: int = channel_recv(ch)
if val == -1 {
running = false
} else {
print("received: " + int_to_string(val))
}
}
thread_join(h)
channel_destroy(ch)
print("done")
return 0
}
Output
received: 0 received: 1 received: 2 received: 3 received: 4 done
Explanation
Channels in Nyx use the Map type as their declaration type -- this is a key detail to remember. channel_new(10) creates a buffered channel that can hold up to 10 values before a sender blocks.
The producer sends integers 0 through 4, then sends -1 as a sentinel value to signal completion. The main thread loops calling channel_recv, which blocks until data is available, and stops when it receives the sentinel.
Always call channel_destroy after both sender and receiver are done to free the underlying resources. The thread_join call ensures the producer has finished before cleanup.