Skip to main content

spawn_worker

Function spawn_worker 

Source
pub(crate) fn spawn_worker(
    slot: &Mutex<Option<JoinHandle<()>>>,
    inner: &Arc<Inner>,
    name: &str,
    body: impl FnOnce() + Send + 'static,
) -> Option<ThreadId>
Expand description

Locked takeover + spawn of a worker thread, shared by the capture and playback starts. Returns the new thread’s id, or None if the spawn failed.

Under the lifecycle lock, in order:

  1. Stop and join any prior worker: sets the external stop INSIDE the lock, immediately before join(), then clears capture_tid — the set-before-join ordering that makes the lost-stop invariant hold.
  2. Reset the lifecycle state: clears stop_state back to STOP_NONE (done ONLY here, under the lock, after the join and before the spawn, where no external stop can be in flight), forgets the previous run’s last_error, and arms the startup handshake at ST_STARTING.
  3. Spawn body on a named thread: the thread applies a best-effort nice boost (audio must not stutter when the captured workload saturates the CPU; EPERM without CAP_SYS_NICE is silently a no-op), publishes its OS tid into capture_tid for the re-entrancy guard, runs body, then clears the tid on exit.

The returned ThreadId is the identity a failed start later hands to join_failed_start, so a losing start tears down only the thread it spawned.