Run background threads below normal priority (#30) #35

Merged
nessar merged 1 commits from perf/30-background-low-priority into main 2026-11-17 19:42:07 +01:00
+36
View File
@@ -63,9 +63,33 @@ fn now_ms() -> i64 {
.map_or(0, |d| d.as_millis() as i64)
}
#[cfg(windows)]
const THREAD_PRIORITY_BELOW_NORMAL: i32 = -1;
#[cfg(windows)]
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetCurrentThread() -> *mut core::ffi::c_void;
fn SetThreadPriority(thread: *mut core::ffi::c_void, priority: i32) -> i32;
#[cfg(test)]
fn GetThreadPriority(thread: *mut core::ffi::c_void) -> i32;
}
/// Lowers the calling thread's priority: background work must not take CPU from the game or the
/// UI (rule #1, budget 5). Best effort: on failure the work still runs.
// shortcut: ureq starts a short DNS thread per request (the core's agents set a timeout) and it
// runs at normal priority; resolve on the calling thread if those threads ever show up in a profile.
fn lower_priority() {
#[cfg(windows)]
unsafe {
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
}
/// Runs `body` on its own thread; a panic is reported instead of leaving the page waiting.
fn spawn_guarded(tx: Sender<Msg>, body: impl FnOnce(&Sender<Msg>) + Send + 'static) {
thread::spawn(move || {
lower_priority();
if catch_unwind(AssertUnwindSafe(|| body(&tx))).is_err() {
let _ = tx.try_send(Msg::Crashed);
}
@@ -154,4 +178,16 @@ mod tests {
assert!(!gate.running());
assert!(!gate.finished());
}
#[cfg(windows)]
#[test]
fn guarded_threads_run_below_normal_priority() {
let (tx, _rx) = std::sync::mpsc::channel();
let (priority_tx, priority_rx) = std::sync::mpsc::channel();
spawn_guarded(tx, move |_| {
let priority = unsafe { GetThreadPriority(GetCurrentThread()) };
priority_tx.send(priority).unwrap();
});
assert_eq!(priority_rx.recv().unwrap(), THREAD_PRIORITY_BELOW_NORMAL);
}
}