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)runsf(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
platbelong to the UI thread: the first thread that uses them (the oneui::launchruns 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 andplat::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=0turns it off (section 12).Background work:
plat::Job--set(count, f)with a'static + Send + Syncclosure (share data throughalloc::sync::Arc),start(),done(),wait(),cancel(),items_done(). When it finishes the pool callsplat::wake(), which arrives asApp::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 Non the command line sets the pool size. Test scripts wait for jobs withsynconce the app installsui.sync_hook_set(Some(f))(f() -> truewhile 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 beSend(anRc<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 aTaskinside another task givesResult<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::Progressreport 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_filewith aCtl(progress in bytes, the cancel token, the chunk size);Reader::open/read(max)andWriter::create/write/commitchunk by chunk. Writes are atomic likeplat::write_file(plat::AtomicFile, see VFS.md): cancelled, failed or dropped, the sibling is removed and the old file stays. AWriter::writewhose 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_asyncanddownload(url, headers, name, &ctl)do the same for HTTP.- Test scripts stay deterministic:
syncwaits until no task work is in flight (pool jobs and the wake-ups they send),wait MSmoves the task clock (sleepfollows the virtual clock in headless runs); wake-ups from other threads reach headless tasks only atsyncand inwait real MS(real time for an app's own threads, section 12).apps/asynctestshows 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).