JFLib

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() -> u64 the task clock in microseconds: time_us(), or the virtual time clock_set gave

  • fn 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 Executor one thread's tasks (see the head of task.rs)

impl Executor

  • fn ui() -> Executor the UI thread's executor: other threads' wake-ups post plat::wake (E_WAKE)

  • fn new() -> Executor an executor that parks this thread while it waits (block_on)

  • fn spawner(&self) -> Spawner a 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) -> bool take the wake-ups other threads sent (the UI calls it for E_WAKE) -> any

  • fn run(&mut self) -> usize fire this thread's due timers, run a queued blocking job where no thread can start, poll every woken task once -> the number of polls

  • fn has_ready(&self) -> bool tasks to poll now (woken or new, a blocking job to run inline)

  • fn busy(&self) -> bool work in flight: ready tasks, wake-ups of other threads not taken yet, blocking jobs (the scripts' sync waits until it is false; tasks waiting for timers do not count)

  • fn live(&self) -> usize tasks alive (spawned, not finished)

  • fn block_on<F: Future>(&mut self, fut: F) -> F::Output run 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::Output run fut to its end on this thread (a parking executor; console programs, tests)

  • struct Spawner spawns 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 run

  • struct 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) -> bool finished, cancelled or dropped by its executor (the future is gone or goes with the executor's next run)

  • fn is_cancelled(&self) -> bool it ended without a value: cancel() came first, or its executor went away

  • fn 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 handle

  • fn sleep(ms: u32) -> Sleep a future ready ms milliseconds of the task clock from now

  • fn sleep_until(at_us: u64) -> Sleep a future ready when the task clock reaches at_us

  • struct Sleep the future of sleep / sleep_until

impl Sleep

  • fn deadline(&self) -> u64 when it is ready (task clock, us)

  • fn fire_timers(now: u64) -> usize wake this thread's timers that are due at now, earliest deadline first -> how many

  • fn next_timer() -> Option<u64> the earliest timer of this thread (task clock, us)

  • fn yield_now() -> YieldNow a future that lets the executor's other tasks run once

  • struct YieldNow(bool) the future of yield_now

  • fn blocking_pending() -> u32 blocking jobs submitted and not finished yet (every executor's)

  • struct Blocking<T> the result of spawn_blocking: a future of f's value

  • fn 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) -> bool the 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() -> CancelToken a token that is not cancelled

  • fn cancel(&self) set the flag; every cancelled() future and run() wrapper wakes up

  • fn is_cancelled(&self) -> bool cancel() was called

  • fn check(&self) -> Result<(), Cancelled> Err(Cancelled) once the token is cancelled (token.check()? between chunks)

  • fn cancelled(&self) -> WaitCancelled a future that is ready once the token is cancelled

  • fn run<F: Future>(&self, fut: F) -> Guarded<F> fut until the token is cancelled: Ok(its value), or Err(Cancelled) (fut is dropped)

  • struct WaitCancelled the future of CancelToken::cancelled

  • struct Guarded<F: Future> the future of CancelToken::run

  • struct Progress(Arc<ProgInner>) the progress of an operation: the worker reports, the UI reads (cheap clones share it)

impl Progress

  • fn new() -> Progress nothing done, total unknown

  • fn set_total(&self, n: u64) the amount of work (bytes, items); 0 = unknown

  • fn set(&self, done: u64) the work done so far

  • fn add(&self, n: u64) n more done

  • fn done(&self) -> u64 the work done so far

  • fn total(&self) -> u64 the amount of work (0: unknown)

  • fn permille(&self) -> u32 done / total in 0..=1000 (0 while the total is unknown)

  • fn reports(&self) -> u64 reports so far (changed() waits for the next one)

  • fn changed(&self) -> Changed a future that is ready after the next report

  • struct Changed the future of Progress::changed

  • struct Join<A: Future, B: Future>(MaybeDone<A>, MaybeDone<B>) the future of join

  • fn 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 join3

  • fn join3<A: Future, B: Future, C: Future>(a: A, b: B, c: C) -> Join3<A, B, C> three futures concurrently -> their values

  • struct JoinAll<F: Future>(Vec<MaybeDone<F>>) the future of join_all

  • fn join_all<F: Future>(v: impl IntoIterator<Item = F>) -> JoinAll<F> every future concurrently -> their values in order

  • enum Either<A, B> which of two futures finished first

    • Left(A)
    • Right(B)
  • struct Select<A: Future, B: Future>(Pin<Box<A>>, Pin<Box<B>>) the future of select

  • fn 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

Source: docs/API.md in the JFLib repository.