Nyx by Example

Thread Spawn

thread_spawn(fn) starts a new OS thread that runs the given function concurrently. thread_join(handle) blocks the calling thread until the spawned thread finishes and returns its integer result. This is the foundational concurrency primitive in Nyx.

Code

// Threads: thread_spawn() para crear un hilo, thread_join() para esperar

fn tarea_hilo() -> int {
    print("from thread")
    return 42
}

fn calcular_cuadrado() -> int {
    let n: int = 7
    return n * n
}

fn main() -> int {
    print("from main (antes de spawn)")

    // Crear un thread y esperar su resultado
    let handle: int = thread_spawn(tarea_hilo)
    let resultado: int = thread_join(handle)
    print("thread retorno: " + int_to_string(resultado))

    // Segundo thread con cálculo
    let h2: int = thread_spawn(calcular_cuadrado)
    let r2: int = thread_join(h2)
    print("7^2 = " + int_to_string(r2))

    print("from main (despues de join)")

    return 0
}

Output

from main (antes de spawn)
from thread
thread retorno: 42
7^2 = 49
from main (despues de join)

Explanation

thread_spawn accepts a function reference (not a closure with captures) and returns an opaque integer handle representing the running thread. The spawned function must have the signature () -> int. Execution of main and the spawned thread proceeds in parallel — in this example the thread prints before thread_join returns, but the exact interleaving is OS-dependent.

thread_join(handle) waits for the thread to finish and retrieves its return value as an int. This is the standard fork-join pattern: spawn work, do other things (or spawn more threads), then collect results. The return value of tarea_hilo is 42, and calcular_cuadrado returns 7 * 7 = 49.

Threads in Nyx run on the OS thread pool and are integrated with the Boehm garbage collector (GC_THREADS is enabled in the runtime). For higher-level concurrency patterns, see the spawn/select goroutine primitives and the M:N work-stealing scheduler in later recipes.

← Previous Next →

Source: examples/by-example/40-thread-spawn.nx