Nyx by Example

Select Channel

The select statement multiplexes multiple channels, waiting for the first one that has data available. Each case names a channel variable. This is similar to Go's select statement.

Code

// Select — multiplexing multiple channels
// Select — multiplexar múltiples canales

var ch1: Map = Map.new()
var ch2: Map = Map.new()

fn sender1() -> int {
    sleep(10)
    channel_send(ch1, 42)
    return 0
}

fn sender2() -> int {
    sleep(20)
    channel_send(ch2, 99)
    return 0
}

fn main() -> int {
    ch1 = channel_new(1)
    ch2 = channel_new(1)

    thread_spawn(sender1)
    thread_spawn(sender2)

    // Select waits for the first channel that has data
    // and executes the matching case block
    var received: int = 0
    while received < 2 {
        select {
            case ch1 => {
                let val: int = channel_recv(ch1)
                print("from ch1: " + int_to_string(val))
                received = received + 1
            }
            case ch2 => {
                let val: int = channel_recv(ch2)
                print("from ch2: " + int_to_string(val))
                received = received + 1
            }
        }
    }

    print("both received")
    return 0
}

Output

from ch1: 42
from ch2: 99
both received

Explanation

The select statement monitors multiple channels simultaneously. When data becomes available on any channel, the corresponding case branch executes. If multiple channels have data, one is chosen.

Two sender threads send values after different delays (10ms and 20ms). The main thread uses select inside a loop to receive from whichever channel is ready first. Since sender1 sleeps less, ch1 typically delivers first.

Channels are declared as Map type -- this is a Nyx-specific detail. The select pattern is essential for building event-driven systems, timeouts, and fan-in multiplexers where you need to react to the first available signal from multiple sources.

← Previous Next →

Source: examples/by-example/63-select-channel.nx