plat/task.rs#
Source: lib/plat/task.rs
task -- async execution: core::future on the thread that owns an executor, blocking work on
a pool, timers, cancellation, joins (task.rs)
Executor::ui() the executor of the UI thread: a wake-up from another thread
posts plat::wake (E_WAKE); lib/ui runs it between passes
(ui.spawn), web / Android from the host's frame callback
Executor::new() an executor that parks its thread (block_on, console programs)
exec.spawn(fut) -> Task<T> fut runs on the executor's thread (it need not be Send)
exec.spawner() -> Spawner spawn from inside tasks (a clone moves into them)
exec.run() -> polled fire the thread's due timers, run queued blocking jobs where
there are no threads, poll every woken task once
exec.accept_remote() -> bool (Executor::ui) take the wake-ups that came from other threads;
the UI calls it for E_WAKE, so headless scripts see them only
at `sync` (deterministic)
exec.has_ready() / busy() / live() work to poll now / work in flight (`sync`) / tasks alive
exec.block_on(fut), block_on(fut) run until fut is done (spawned tasks run alongside)
Task<T>: is_done / is_cancelled / take / cancel / detach; awaiting it gives Result<T,
Cancelled>; dropping the handle cancels the task (detach keeps it running)
spawn_blocking(f) -> Blocking<T> f on a thread of the blocking pool (files, network,
parallel_for); spawn_cancellable(f(&token)): token is
cancelled once nobody awaits the result (a job not started
then never starts). A caller inside policy's trusted() keeps
that on the pool thread. blocking_pending() -> jobs in flight
sleep(ms) / sleep_until(us) timers of the polling thread's executor on now_us()
now_us() / clock_set(Some(us) | None) the task clock: time_us(), or the virtual clock of
headless UI runs (scripts' `wait`)
next_timer() -> Option<us> the earliest timer of this thread (event loop deadlines)
CancelToken: cancel / is_cancelled / check / cancelled() future / run(fut) -> Result<T,
Cancelled> (fut is dropped when the token wins)
Progress: set_total / set / add / done / total / permille / changed() future; a report
wakes the event loop (at most every PROGRESS_WAKE_MS, always at the end)
join(a, b) / join3(a, b, c) / join_all(v) / select(a, b) -> Either / yield_now()
Design. An executor keeps its tasks in slots; a task's Waker (alloc::task::Wake, no unsafe)
names slot and version and queues itself once until it is polled again. Wake-ups on the
owning thread go to the local list, those from other threads to the remote list plus a signal
(plat::wake for the UI, the park semaphore for block_on); the UI takes remote ones only with
E_WAKE. Timers live in one list with the thread that registered them; each executor fires
its own. Blocking jobs run on up to BLOCKING_MAX threads of their own (not the compute pool:
a job waiting for a disk must not starve parallel_for); where no thread can start (the
browser without shared memory) the executors run them inline, one per run. A panic
in a task or job ends the process like any panic (rt's handler: crash hook, exit code 3), with
jflib's feature unwind too unless the task's own code catches it (rt::abort_on_unwind).
/// threads of the blocking pool at most (more jobs wait in its queue)
BLOCKING_MAX: u32 = 8
/// a Progress report wakes the event loop at most this often (the last one always)
PROGRESS_WAKE_MS: u64 = 30
fn now_us() -> u64the task clock in microseconds: time_us(), or the virtual time clock_set gavefn clock_set(us: Option<u64>)Some(us): the task clock stands at us until the next call (headless UI runs drive it with the script's virtual clock); None: back to time_us()struct Executorone thread's tasks (see the head of task.rs)
impl Executor
fn ui() -> Executorthe UI thread's executor: other threads' wake-ups post plat::wake (E_WAKE)fn new() -> Executoran executor that parks this thread while it waits (block_on)fn spawner(&self) -> Spawnera handle that spawns onto this executor (from inside its tasks)fn spawn<F: Future + 'static>(&self, fut: F) -> Task<F::Output>run fut on this executor's thread; it starts with the next run()fn accept_remote(&mut self) -> booltake the wake-ups other threads sent (the UI calls it for E_WAKE) -> anyfn run(&mut self) -> usizefire this thread's due timers, run a queued blocking job where no thread can start, poll every woken task once -> the number of pollsfn has_ready(&self) -> booltasks to poll now (woken or new, a blocking job to run inline)fn busy(&self) -> boolwork in flight: ready tasks, wake-ups of other threads not taken yet, blocking jobs (the scripts'syncwaits until it is false; tasks waiting for timers do not count)fn live(&self) -> usizetasks alive (spawned, not finished)fn block_on<F: Future>(&mut self, fut: F) -> F::Outputrun until fut is done; the executor's other tasks run alongside. The thread sleeps on a semaphore between wake-ups (Executor::ui: it only yields, and takes other threads' wake-ups itself: no event loop runs meanwhile)fn block_on<F: Future>(fut: F) -> F::Outputrun fut to its end on this thread (a parking executor; console programs, tests)struct Spawnerspawns onto the executor it came from (clone it into tasks)
impl Spawner
fn spawn<F: Future + 'static>(&self, fut: F) -> Task<F::Output>run fut on the executor's thread; it starts with the executor's next runstruct Task<T>the handle of a spawned task; dropping it cancels the task (detach keeps it running)
impl<T> Task<T>
fn is_done(&self) -> boolfinished, cancelled or dropped by its executor (the future is gone or goes with the executor's next run)fn is_cancelled(&self) -> boolit ended without a value: cancel() came first, or its executor went awayfn take(&self) -> Option<T>the result, once (None: still running, cancelled or already taken)fn cancel(&self)stop the task: its future is dropped at the executor's next run (a finished task keeps its result)fn detach(mut self)let the task run on without a handlefn sleep(ms: u32) -> Sleepa future ready ms milliseconds of the task clock from nowfn sleep_until(at_us: u64) -> Sleepa future ready when the task clock reaches at_usstruct Sleepthe future of sleep / sleep_until
impl Sleep
fn deadline(&self) -> u64when it is ready (task clock, us)fn fire_timers(now: u64) -> usizewake this thread's timers that are due at now, earliest deadline first -> how manyfn next_timer() -> Option<u64>the earliest timer of this thread (task clock, us)fn yield_now() -> YieldNowa future that lets the executor's other tasks run oncestruct YieldNow(bool)the future of yield_nowfn blocking_pending() -> u32blocking jobs submitted and not finished yet (every executor's)struct Blocking<T>the result of spawn_blocking: a future of f's valuefn spawn_blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Blocking<T>run f on the blocking pool (a thread of its own: files, network, parallel_for loops)fn spawn_cancellable<T: Send + 'static>(f: impl FnOnce(&CancelToken) -> T + Send + 'static) -> Blocking<T>run f on the blocking pool; its token is cancelled when the Blocking future is dropped before the result was taken (a job not started yet is skipped)
impl<T> Blocking<T>
fn is_done(&self) -> boolthe job has finished (polling gives its value now)struct CancelToken(Arc<CancelInner>)a shared cancel flag: cancel() from any thread, checked between chunks of work or awaited
impl CancelToken
fn new() -> CancelTokena token that is not cancelledfn cancel(&self)set the flag; every cancelled() future and run() wrapper wakes upfn is_cancelled(&self) -> boolcancel() was calledfn check(&self) -> Result<(), Cancelled>Err(Cancelled) once the token is cancelled (token.check()?between chunks)fn cancelled(&self) -> WaitCancelleda future that is ready once the token is cancelledfn run<F: Future>(&self, fut: F) -> Guarded<F>fut until the token is cancelled: Ok(its value), or Err(Cancelled) (fut is dropped)struct WaitCancelledthe future of CancelToken::cancelledstruct Guarded<F: Future>the future of CancelToken::runstruct Progress(Arc<ProgInner>)the progress of an operation: the worker reports, the UI reads (cheap clones share it)
impl Progress
fn new() -> Progressnothing done, total unknownfn set_total(&self, n: u64)the amount of work (bytes, items); 0 = unknownfn set(&self, done: u64)the work done so farfn add(&self, n: u64)n more donefn done(&self) -> u64the work done so farfn total(&self) -> u64the amount of work (0: unknown)fn permille(&self) -> u32done / total in 0..=1000 (0 while the total is unknown)fn reports(&self) -> u64reports so far (changed() waits for the next one)fn changed(&self) -> Changeda future that is ready after the next reportstruct Changedthe future of Progress::changedstruct Join<A: Future, B: Future>(MaybeDone<A>, MaybeDone<B>)the future of joinfn join<A: Future, B: Future>(a: A, b: B) -> Join<A, B>both futures, concurrently on the same task -> (a's value, b's value)struct Join3<A: Future, B: Future, C: Future>(MaybeDone<A>, MaybeDone<B>, MaybeDone<C>)the future of join3fn join3<A: Future, B: Future, C: Future>(a: A, b: B, c: C) -> Join3<A, B, C>three futures concurrently -> their valuesstruct JoinAll<F: Future>(Vec<MaybeDone<F>>)the future of join_allfn join_all<F: Future>(v: impl IntoIterator<Item = F>) -> JoinAll<F>every future concurrently -> their values in orderenum Either<A, B>which of two futures finished firstLeft(A)Right(B)
struct Select<A: Future, B: Future>(Pin<Box<A>>, Pin<Box<B>>)the future of selectfn select<A: Future, B: Future>(a: A, b: B) -> Select<A, B>the first of two futures to finish (polled in order a, b); the other one is dropped