JFLib

9. Threads#

plat has a worker pool (legacy/ASMLIB/docs/modules/THREADS.md describes the design; the Rust pool is the same). Results must not depend on the number of threads: give every item a fixed piece of work.

/// brighten every pixel of a straight-ARGB surface on all cores
fn brighten(sf: &mut gfx::Surface, add: u8) {
    let stride = sf.stride as usize;
    let w = sf.w as usize;
    // one item per band of 64 rows; each item locks only its own band
    let bands: Vec<SpinLock<&mut [u8]>> = sf.px.chunks_mut(stride * 64).map(SpinLock::new).collect();
    let item = |i: usize, job: &plat::JobCtl| {
        let mut band = bands[i].lock();
        for row in band.chunks_mut(stride) {
            if job.cancelled() {
                return;
            }
            for px in row[..w * 4].chunks_exact_mut(4) {
                for c in &mut px[..3] {
                    *c = c.saturating_add(add);
                }
            }
        }
    };
    let _ = plat::parallel_for(bands.len(), &item); // returns when every item is done
}

(SpinLock is rt::sync::SpinLock.)

  • parallel_for(count, &f) runs f(index, job) on the workers and the calling thread; nested loops are fine; job.cancel() skips the remaining items -> Err(Cancelled).

  • The windows, the clipboard, the dialogs and the portals of plat belong to the UI thread: the first thread that uses them (the one ui::launch runs on). On any other thread such a call panics before it touches anything (Windows, Linux with X11 and the portals, macOS, iOS); hand the work to the UI thread instead (a channel and plat::wake()).

  • The renderer uses the pool too: a redraw of about 3 million pixels or more (1.5 times 1920 x 1080), in a framebuffer of more than 16 MB (4K, 8K) of 750 000 pixels or more, is cut into row bands that the workers draw into buffers of their own (ui/render_par.rs), with the bytes one thread draws. Texts and font icons are placed on the UI thread first (Text::record_n, the glyph masks go into the cache), the workers blend them read-only (text::GlyphView). Canvases (Draw), icons an icon hook or the style paints and glyphs too large for the cache are drawn on the UI thread: the workers draw their bands up to the first of them, the UI thread the rest. Without workers (the browser without shared memory) everything stays on one thread; jfgui_RENDER_PAR=0 turns it off (section 12).

  • Background work: plat::Job -- set(count, f) with a 'static + Send + Sync closure (share data through alloc::sync::Arc), start(), done(), wait(), cancel(), items_done(). When it finishes the pool calls plat::wake(), which arrives as App::command(UIC_WAKE, 0):

    struct Loader {
        job: plat::Job,
        result: Arc<SpinLock<Option<Result<gfx::Surface, i32>>>>,
    }
    
    impl Loader {
        fn start(&mut self, path: String) {
            let slot = self.result.clone();
            self.job.set(1, move |_, _| {
                let r = img_core::io::load_ex(&path, None, None);
                *slot.lock() = Some(r);
            });
            self.job.start(); // UIC_WAKE when it is done
        }
        // in App::command(UIC_WAKE)
        fn poll(&mut self) -> Option<Result<gfx::Surface, i32>> {
            if !self.job.done() {
                return None;
            }
            self.result.lock().take()
        }
    }
  • thr_count() workers, thr_self() a per-thread slot index; --threads N on the command line sets the pool size. Test scripts wait for jobs with sync once the app installs ui.sync_hook_set(Some(f)) (f() -> true while work is pending).

Async tasks: ui.spawn, plat::task, plat::aio#

Work that waits (files, network, timers) is simpler as an async block handed to ui.spawn. It runs on the UI thread between passes, its blocking parts go to a pool of their own, and App::frame looks at the handle: no UIC_WAKE handler, no shared result slots.

use plat::aio::{self, Ctl, IoError};
use plat::task::Task;

struct Copier {
    task: Option<Task<Result<u64, IoError>>>,
    ctl: Ctl, // progress (bytes) and cancel token, shared with the copy
    status: String,
}

impl App for Copier {
    fn frame(&mut self, ui: &mut Ui) {
        if let Some(t) = self.task.as_ref().filter(|t| t.is_done()) {
            self.status = match t.take() {
                Some(Ok(n)) => format!("{n} Bytes kopiert"),
                Some(Err(IoError::Cancelled)) | None => String::from("abgebrochen"),
                Some(Err(e)) => format!("Fehler: {e}"),
            };
            self.task = None;
        }
        ui.progress(1, self.ctl.progress.permille() as i32, 1000);
        ui.text(TS_BODY, &self.status);
        if ui.button(2, "Kopieren") & EV_ACT != 0 && self.task.is_none() {
            self.ctl = Ctl::new();
            self.task = Some(ui.spawn(aio::copy_file("documents://a.bin", "documents://b.bin", &self.ctl)));
        }
        if ui.button(3, "Abbrechen") & EV_ACT != 0 {
            self.ctl.cancel.cancel(); // stops between two chunks; b.bin stays as it was
        }
    }
}
  • ui.spawn(fut) -> Task<T>: the future need not be Send (an Rc<Cell<_>> shared with the app works). task.take() gives the result once; is_done(), is_cancelled(); cancel() drops the future at the next run, with everything it holds; dropping the handle cancels too, detach() lets it run on. Awaiting a Task inside another task gives Result<T, Cancelled>; ui.spawner() spawns from inside tasks.
  • A task that ran gets the app another pass, so the frame sees what it changed. A plat::task::Progress report wakes the event loop (at most every 30 ms, always at the end), so progress bars move while a job runs on another thread.
  • plat::task: spawn_blocking(f) for any blocking call (files, sockets, parallel_for) on a pool of up to 8 threads apart from the compute workers; spawn_cancellable(|token| ..) (the token says nobody waits any more; a job not started yet is skipped); sleep(ms); CancelToken (cancel, is_cancelled, check()?, cancelled().await, run(fut)); join / join3 / join_all / select; yield_now. plat::task::block_on(fut) runs the same code in console programs and tests.
  • plat::aio: read_file, write_file, copy_file with a Ctl (progress in bytes, the cancel token, the chunk size); Reader::open / read(max) and Writer::create / write / commit chunk by chunk. Writes are atomic like plat::write_file (plat::AtomicFile, see VFS.md): cancelled, failed or dropped, the sibling is removed and the old file stays. A Writer::write whose future is dropped before it ends spoils the writer (its job may still write): later writes and the commit fail. Names, mounts and permissions are those of the blocking calls. netio::Client::request_async and download(url, headers, name, &ctl) do the same for HTTP.
  • Test scripts stay deterministic: sync waits until no task work is in flight (pool jobs and the wake-ups they send), wait MS moves the task clock (sleep follows the virtual clock in headless runs); wake-ups from other threads reach headless tasks only at sync and in wait real MS (real time for an app's own threads, section 12). apps/asynctest shows a copy with a progress bar and a cancel button and the scripts that step through it.
  • A panic in a task or a blocking job ends the process like any panic (exit code 3). In the browser without shared memory there are no threads: blocking jobs run between frames on the UI thread, one per run (Android has real threads since AN1, docs/ANDROID.md).

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