Skip to main content

spawn_dedicated_thread

Function spawn_dedicated_thread 

Source
pub fn spawn_dedicated_thread<F, Fut>(
    session_id: SessionId,
    scheduler: Arc<dyn Scheduler>,
    f: F,
) -> Task<Fut::Output> ⓘ
where F: FnOnce(LocalExecutor) -> Fut + Send + 'static, Fut: Future + 'static, Fut::Output: Send + 'static,
Expand description

Spawn work on a fresh OS thread that’s exclusive to the returned task and anything spawned on the executor it provides. Blocking syscalls inside that work don’t disturb any other executor in the process.

f is called on the dedicated thread with a LocalExecutor pinned to it. The future f returns may freely be !Send. The returned Task resolves to that future’s output: dropping it cancels the root, but detached children keep running until they finish. The thread shuts down once the executor and every task on it are gone.

This function never blocks: the returned task starts as an asynchronous rendezvous that resolves to the root task’s handle once the dedicated thread has spawned it, and behaves like that handle from then on. That makes it safe to call from threads that must not block, such as the web main thread. On wasm targets the thread is a web worker and requires the wasm-threads cargo feature (and a shared-memory build); without it this panics. Spawning a worker is far more expensive than an OS thread — module instantiation plus a fresh function table — so on the web treat a dedicated session as a long-lived place to send work, not a per-job convenience.

The caller is responsible for supplying a session_id that’s distinct from every other live session on scheduler. Concrete schedulers typically wrap this in an inherent method that allocates the id from their own counter.