Persistent worker pools instead of per-frame and per-tile threads
Browse files at this commita02c7bd8ec57de25b9705594bff52add71bcb857Parent: 33312b9- perf
- persistent worker pools instead of per-frame and per-tile threads
3 changed files +212 -23
- crates/ec-av1/src/decode.rs +15 -11
- crates/ec-av1/src/par.rs +189 -8
- crates/ec-av1/src/stream.rs +8 -4
crates/ec-av1/src/decode.rsmodified+15 -11
| @@ -2425,7 +2425,13 @@ fn wave_worker(st: &WaveState) { | |||
| 2425 | /// Installs the wavefront for one tile and joins its workers on every exit | 2425 | /// Installs the wavefront for one tile and joins its workers on every exit |
| 2426 | /// from the tile decoder, including the `?` ones -- the jobs hold raw | 2426 | /// from the tile decoder, including the `?` ones -- the jobs hold raw |
| 2427 | /// pointers into the tile's planes, so no worker may outlive them. | 2427 | /// pointers into the tile's planes, so no worker may outlive them. |
| 2428 | -pub(crate) struct WaveGuard<'a>(&'a crate::decode::FrameCtx, Vec<std::thread::JoinHandle<()>>); | 2428 | +/// (lane-pool1: the workers come from this thread's persistent pool, so a |
| 2429 | +/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads | ||
| 2430 | +/// with fresh scratch.) | ||
| 2431 | +pub(crate) struct WaveGuard<'a>( | ||
| 2432 | + &'a crate::decode::FrameCtx, | ||
| 2433 | + Option<crate::par::Batch<'static>>, | ||
| 2434 | +); | ||
| 2429 | 2435 | ||
| 2430 | #[allow(unsafe_code)] | 2436 | #[allow(unsafe_code)] |
| 2431 | impl<'a> WaveGuard<'a> { | 2437 | impl<'a> WaveGuard<'a> { |
| @@ -2460,14 +2466,13 @@ impl<'a> WaveGuard<'a> { | |||
| 2460 | enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get), | 2466 | enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get), |
| 2461 | last_col: cols - 1, | 2467 | last_col: cols - 1, |
| 2462 | }); | 2468 | }); |
| 2463 | - let workers = (0..threads) | 2469 | + let batch = crate::par::Batch::new(); |
| 2464 | - .map(|_| { | 2470 | + for _ in 0..threads { |
| 2465 | - let st = std::sync::Arc::clone(&st); | 2471 | + let st = std::sync::Arc::clone(&st); |
| 2466 | - std::thread::spawn(move || wave_worker(&st)) | 2472 | + batch.submit(move || wave_worker(&st)); |
| 2467 | - }) | 2473 | + } |
| 2468 | - .collect(); | ||
| 2469 | fctx.wave.with(|w| *w.borrow_mut() = Some(st)); | 2474 | fctx.wave.with(|w| *w.borrow_mut() = Some(st)); |
| 2470 | - Some(Self(fctx, workers)) | 2475 | + Some(Self(fctx, Some(batch))) |
| 2471 | } | 2476 | } |
| 2472 | } | 2477 | } |
| 2473 | 2478 | ||
| @@ -2478,9 +2483,8 @@ impl Drop for WaveGuard<'_> { | |||
| 2478 | st.q.lock().unwrap().closed = true; | 2483 | st.q.lock().unwrap().closed = true; |
| 2479 | st.cv.notify_all(); | 2484 | st.cv.notify_all(); |
| 2480 | } | 2485 | } |
| 2481 | - for h in self.1.drain(..) { | 2486 | + // Dropping the batch waits every worker out, as the joins did. |
| 2482 | - let _ = h.join(); | 2487 | + drop(self.1.take()); |
| 2483 | - } | ||
| 2484 | } | 2488 | } |
| 2485 | } | 2489 | } |
| 2486 | 2490 | ||
crates/ec-av1/src/par.rsmodified+189 -8
| @@ -122,14 +122,17 @@ where | |||
| 122 | [] => {} | 122 | [] => {} |
| 123 | [(a, b)] => f(*a, *b, fctx), | 123 | [(a, b)] => f(*a, *b, fctx), |
| 124 | [(a0, b0), rest @ ..] => { | 124 | [(a0, b0), rest @ ..] => { |
| 125 | - std::thread::scope(|s| { | 125 | + // lane-pool1: same shape as the `thread::scope` this replaced -- |
| 126 | - for &(a, b) in rest { | 126 | + // band 0 inline, the rest on this thread's persistent pool, all |
| 127 | - let ctx = crate::decode::filter_ctx_copy(fctx); | 127 | + // waited out by `batch`'s drop at the end of the block. |
| 128 | - let f = &f; | 128 | + let batch = Batch::new(); |
| 129 | - s.spawn(move || f(a, b, &ctx)); | 129 | + for &(a, b) in rest { |
| 130 | - } | 130 | + let ctx = crate::decode::filter_ctx_copy(fctx); |
| 131 | - f(*a0, *b0, fctx); | 131 | + let f = &f; |
| 132 | - }); | 132 | + batch.submit(move || f(a, b, &ctx)); |
| 133 | + } | ||
| 134 | + f(*a0, *b0, fctx); | ||
| 135 | + drop(batch); | ||
| 133 | } | 136 | } |
| 134 | } | 137 | } |
| 135 | } | 138 | } |
| @@ -161,3 +164,181 @@ pub(crate) fn recon_threads() -> usize { | |||
| 161 | pub(crate) fn set_recon_threads(n: usize) { | 164 | pub(crate) fn set_recon_threads(n: usize) { |
| 162 | RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); | 165 | RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); |
| 163 | } | 166 | } |
| 167 | + | ||
| 168 | +// --- lane-pool1: persistent worker pools --------------------------------- | ||
| 169 | +// | ||
| 170 | +// Every threaded stage of the decoder used to spawn its threads per unit of | ||
| 171 | +// work: one `thread::scope` per filter STAGE per frame, `EC_AV1_RECON_THREADS` | ||
| 172 | +// workers per TILE, one frame worker per coded frame -- 2363 distinct threads | ||
| 173 | +// in a 13 s 4K decode. The cost is not the clone of the thread itself but what | ||
| 174 | +// dies with it: every `thread_local!` scratch pool in `decode.rs` (planes, | ||
| 175 | +// rows, dq, mc, wiener, sgr) is allocated and faulted in again on each new | ||
| 176 | +// thread, which is where the 3.65 M page faults and the 2.7x malloc traffic of | ||
| 177 | +// the composed setting came from. | ||
| 178 | +// | ||
| 179 | +// The replacement is one pool per POOL-OWNING THREAD, kept in a thread-local | ||
| 180 | +// and joined when that thread exits: a stage submits a [`Batch`] of jobs, the | ||
| 181 | +// pool hands each to an idle worker (growing to `busy + queued` so a job never | ||
| 182 | +// queues behind a blocking one -- the recon wavefront's workers block on their | ||
| 183 | +// dependencies), and the batch's `Drop` waits every job out. Scratch then | ||
| 184 | +// lives as long as the worker, not as long as the frame. | ||
| 185 | +type Job = Box<dyn FnOnce() + Send + 'static>; | ||
| 186 | + | ||
| 187 | +struct PoolQ { | ||
| 188 | + jobs: std::collections::VecDeque<Job>, | ||
| 189 | + /// Jobs handed to a worker and not yet finished. | ||
| 190 | + busy: usize, | ||
| 191 | + closed: bool, | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +struct PoolInner { | ||
| 195 | + q: std::sync::Mutex<PoolQ>, | ||
| 196 | + cv: std::sync::Condvar, | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +struct Pool { | ||
| 200 | + inner: std::sync::Arc<PoolInner>, | ||
| 201 | + handles: Vec<std::thread::JoinHandle<()>>, | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +fn pool_worker(inner: &PoolInner) { | ||
| 205 | + let mut q = inner.q.lock().unwrap(); | ||
| 206 | + loop { | ||
| 207 | + if let Some(job) = q.jobs.pop_front() { | ||
| 208 | + q.busy += 1; | ||
| 209 | + drop(q); | ||
| 210 | + // A job's own panic is captured by the batch wrapper below, so | ||
| 211 | + // this only guards against a wrapper that itself unwinds. | ||
| 212 | + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); | ||
| 213 | + q = inner.q.lock().unwrap(); | ||
| 214 | + q.busy -= 1; | ||
| 215 | + continue; | ||
| 216 | + } | ||
| 217 | + if q.closed { | ||
| 218 | + return; | ||
| 219 | + } | ||
| 220 | + q = inner.cv.wait(q).unwrap(); | ||
| 221 | + } | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +impl Pool { | ||
| 225 | + fn new() -> Self { | ||
| 226 | + Self { | ||
| 227 | + inner: std::sync::Arc::new(PoolInner { | ||
| 228 | + q: std::sync::Mutex::new(PoolQ { | ||
| 229 | + jobs: std::collections::VecDeque::new(), | ||
| 230 | + busy: 0, | ||
| 231 | + closed: false, | ||
| 232 | + }), | ||
| 233 | + cv: std::sync::Condvar::new(), | ||
| 234 | + }), | ||
| 235 | + handles: Vec::new(), | ||
| 236 | + } | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + /// Queues `job` and makes sure a worker is free for it: the pool grows to | ||
| 240 | + /// `busy + queued` threads and never shrinks, so a submitted job always | ||
| 241 | + /// starts, even when every other running job is blocked waiting for it. | ||
| 242 | + fn push(&mut self, job: Job) { | ||
| 243 | + let want = { | ||
| 244 | + let mut q = self.inner.q.lock().unwrap(); | ||
| 245 | + q.jobs.push_back(job); | ||
| 246 | + q.busy + q.jobs.len() | ||
| 247 | + }; | ||
| 248 | + while self.handles.len() < want { | ||
| 249 | + let inner = std::sync::Arc::clone(&self.inner); | ||
| 250 | + self.handles | ||
| 251 | + .push(std::thread::spawn(move || pool_worker(&inner))); | ||
| 252 | + } | ||
| 253 | + self.inner.cv.notify_one(); | ||
| 254 | + } | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +impl Drop for Pool { | ||
| 258 | + fn drop(&mut self) { | ||
| 259 | + self.inner.q.lock().unwrap().closed = true; | ||
| 260 | + self.inner.cv.notify_all(); | ||
| 261 | + for h in self.handles.drain(..) { | ||
| 262 | + let _ = h.join(); | ||
| 263 | + } | ||
| 264 | + } | ||
| 265 | +} | ||
| 266 | + | ||
| 267 | +thread_local! { | ||
| 268 | + /// This thread's pool, created on its first [`Batch::submit`] and joined | ||
| 269 | + /// when the thread exits (the process's main thread may skip that | ||
| 270 | + /// destructor, in which case the idle workers die with the process). | ||
| 271 | + static POOL: std::cell::RefCell<Option<Pool>> = const { std::cell::RefCell::new(None) }; | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +struct BatchState { | ||
| 275 | + left: std::sync::Mutex<usize>, | ||
| 276 | + cv: std::sync::Condvar, | ||
| 277 | + panic: std::sync::Mutex<Option<Box<dyn std::any::Any + Send>>>, | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +/// A set of jobs running on the submitting thread's pool. `Drop` waits for | ||
| 281 | +/// every one of them and re-raises the first panic, which is what makes | ||
| 282 | +/// [`Batch::submit`]'s borrow of non-`'static` data sound -- exactly | ||
| 283 | +/// `thread::scope`'s contract, minus the spawns. | ||
| 284 | +/// | ||
| 285 | +/// corner-cut: soundness rests on this `Drop` running; `std::mem::forget` of a | ||
| 286 | +/// `Batch` would let a job outlive its borrows. The type is crate-private and | ||
| 287 | +/// every construction site below binds it to a local. Upgrade path is the | ||
| 288 | +/// closure-taking `scope(|s| ...)` shape, which costs every caller a level of | ||
| 289 | +/// indentation for the same guarantee. | ||
| 290 | +pub(crate) struct Batch<'a> { | ||
| 291 | + st: std::sync::Arc<BatchState>, | ||
| 292 | + _p: std::marker::PhantomData<&'a ()>, | ||
| 293 | +} | ||
| 294 | + | ||
| 295 | +impl<'a> Batch<'a> { | ||
| 296 | + pub(crate) fn new() -> Self { | ||
| 297 | + Self { | ||
| 298 | + st: std::sync::Arc::new(BatchState { | ||
| 299 | + left: std::sync::Mutex::new(0), | ||
| 300 | + cv: std::sync::Condvar::new(), | ||
| 301 | + panic: std::sync::Mutex::new(None), | ||
| 302 | + }), | ||
| 303 | + _p: std::marker::PhantomData, | ||
| 304 | + } | ||
| 305 | + } | ||
| 306 | + | ||
| 307 | + pub(crate) fn submit<F: FnOnce() + Send + 'a>(&self, f: F) { | ||
| 308 | + *self.st.left.lock().unwrap() += 1; | ||
| 309 | + let st = std::sync::Arc::clone(&self.st); | ||
| 310 | + let job: Box<dyn FnOnce() + Send + 'a> = Box::new(move || { | ||
| 311 | + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); | ||
| 312 | + if let Err(p) = r { | ||
| 313 | + let mut slot = st.panic.lock().unwrap(); | ||
| 314 | + if slot.is_none() { | ||
| 315 | + *slot = Some(p); | ||
| 316 | + } | ||
| 317 | + } | ||
| 318 | + let mut left = st.left.lock().unwrap(); | ||
| 319 | + *left -= 1; | ||
| 320 | + st.cv.notify_all(); | ||
| 321 | + }); | ||
| 322 | + // SAFETY: the job is dropped before `Batch::drop` returns (it waits | ||
| 323 | + // for `left == 0`), and `Batch<'a>` cannot outlive `'a`, so the | ||
| 324 | + // laundered lifetime is never observed past the real one. | ||
| 325 | + let job: Job = unsafe { std::mem::transmute::<Box<dyn FnOnce() + Send + 'a>, Job>(job) }; | ||
| 326 | + POOL.with(|p| { | ||
| 327 | + let mut p = p.borrow_mut(); | ||
| 328 | + p.get_or_insert_with(Pool::new).push(job); | ||
| 329 | + }); | ||
| 330 | + } | ||
| 331 | +} | ||
| 332 | + | ||
| 333 | +impl Drop for Batch<'_> { | ||
| 334 | + fn drop(&mut self) { | ||
| 335 | + let mut left = self.st.left.lock().unwrap(); | ||
| 336 | + while *left > 0 { | ||
| 337 | + left = self.st.cv.wait(left).unwrap(); | ||
| 338 | + } | ||
| 339 | + drop(left); | ||
| 340 | + if let Some(p) = self.st.panic.lock().unwrap().take() { | ||
| 341 | + std::panic::resume_unwind(p); | ||
| 342 | + } | ||
| 343 | + } | ||
| 344 | +} | ||
crates/ec-av1/src/stream.rsmodified+8 -4
| @@ -478,7 +478,12 @@ pub fn decode_stream_with_threads( | |||
| 478 | threads: usize, | 478 | threads: usize, |
| 479 | mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, | 479 | mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>, |
| 480 | ) -> Result<()> { | 480 | ) -> Result<()> { |
| 481 | - std::thread::scope(|scope| { | 481 | + // lane-pool1: this replaced a `std::thread::scope` -- frame workers now |
| 482 | + // come from a persistent pool (one per submitting thread, workers reused | ||
| 483 | + // across frames, so their `thread_local!` decode scratch survives the | ||
| 484 | + // frame). `jobs` is declared here and dropped at the end of the function, | ||
| 485 | + // including on `?`, so no job outlives the data it borrows. | ||
| 486 | + let jobs = crate::par::Batch::new(); | ||
| 482 | // lane-thread1: this stream's per-frame decode state (was 38 thread_local | 487 | // lane-thread1: this stream's per-frame decode state (was 38 thread_local |
| 483 | // statics in decode.rs) -- one object, threaded down the decode call graph. | 488 | // statics in decode.rs) -- one object, threaded down the decode call graph. |
| 484 | let fctx = &crate::decode::FrameCtx::new(); | 489 | let fctx = &crate::decode::FrameCtx::new(); |
| @@ -617,7 +622,7 @@ pub fn decode_stream_with_threads( | |||
| 617 | let grain = header.film_grain; | 622 | let grain = header.film_grain; |
| 618 | let seq = SeqFlags::read(&parser); | 623 | let seq = SeqFlags::read(&parser); |
| 619 | let tx = tx.clone(); | 624 | let tx = tx.clone(); |
| 620 | - scope.spawn(move || { | 625 | + jobs.submit(move || { |
| 621 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | 626 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 622 | let value = promise.wait()?; | 627 | let value = promise.wait()?; |
| 623 | let output = if grain.apply_grain && !no_grain() { | 628 | let output = if grain.apply_grain && !no_grain() { |
| @@ -838,7 +843,7 @@ pub fn decode_stream_with_threads( | |||
| 838 | } | 843 | } |
| 839 | let tx = tx.clone(); | 844 | let tx = tx.clone(); |
| 840 | let dump = final_dump.clone(); | 845 | let dump = final_dump.clone(); |
| 841 | - scope.spawn(move || { | 846 | + jobs.submit(move || { |
| 842 | let promise = produces; | 847 | let promise = produces; |
| 843 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { | 848 | let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 844 | // The wait happens HERE, off the parsing thread, and only | 849 | // The wait happens HERE, off the parsing thread, and only |
| @@ -1041,7 +1046,6 @@ pub fn decode_stream_with_threads( | |||
| 1041 | } | 1046 | } |
| 1042 | debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); | 1047 | debug_assert!(reorder.pending.is_empty(), "a frame was never emitted"); |
| 1043 | Ok(()) | 1048 | Ok(()) |
| 1044 | - }) | ||
| 1045 | } | 1049 | } |
| 1046 | 1050 | ||
| 1047 | 1051 | ||