Skip to main content

run

Function run 

Source
pub fn run<F, R>(f: F) -> R
where F: FnOnce() -> R + Send + 'static, R: Send + 'static,
Expand description

Initialise the go-lib scheduler, run f as the first goroutine, and return whatever f returns.

Blocks the calling thread until f returns. The scheduler threads (one per logical CPU) continue running in the background after run returns; they park themselves when there is no more work.

§Parameters

f can capture any values it needs from the surrounding scope via a move closure — there is no need to pass parameters directly to run:

let base = 10_i32;
let result = go_lib::run(move || base * 2);
assert_eq!(result, 20);

§Return values

The closure’s return value is propagated back to the caller:

let sum = go_lib::run(|| {
    let (tx, rx) = go_lib::chan::chan::<i32>(4);
    for i in 1..=4 { let t = tx.clone(); go_lib::__spawn(move || t.send(i)); }
    (0..4).filter_map(|_| rx.recv()).sum::<i32>()
});
assert_eq!(sum, 10);

When the closure returns () (the default), run behaves exactly as before — the return value can simply be ignored.

§Panics

Panics if f panics before producing a return value. A panicking goroutine is caught by the scheduler’s catch_unwind; the panic payload is forwarded to set_panic_handler and the calling thread is woken with an expect failure.