forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

pool.rs81 lines, 2.7 KiBHistoryRawDownload
1//! Persistent band workers for the slice-parallel encoder.
2//!
3//! One thread per band, started once and fed one job per picture over a
4//! channel, so a picture costs a send and a receive per band instead of a
5//! thread spawn and join. Created by the encoder on its first multi-band
6//! picture and joined when the encoder is dropped. std only.
7
8use std::sync::mpsc::{Receiver, Sender, channel};
9use std::thread::JoinHandle;
10
11/// A fixed set of worker threads, each applying one function to the jobs
12/// sent to it, in order.
13pub(super) struct BandPool<J: Send + 'static, R: Send + 'static> {
14 lanes: Vec<Lane<J, R>>,
15}
16
17struct Lane<J, R> {
18 /// Taken on drop, which ends the worker's loop.
19 jobs: Option<Sender<J>>,
20 done: Receiver<R>,
21 handle: Option<JoinHandle<()>>,
22}
23
24impl<J: Send + 'static, R: Send + 'static> BandPool<J, R> {
25 /// `n` idle workers, each running `work` on the jobs it is sent.
26 pub(super) fn new(n: usize, work: fn(J) -> R) -> Self {
27 let lanes = (0..n)
28 .map(|i| {
29 let (jobs, job_rx) = channel::<J>();
30 let (done_tx, done) = channel::<R>();
31 let handle = std::thread::Builder::new()
32 .name(format!("ec-h264-band-{i}"))
33 .spawn(move || {
34 while let Ok(job) = job_rx.recv() {
35 if done_tx.send(work(job)).is_err() {
36 break;
37 }
38 }
39 })
40 .expect("start a band worker thread");
41 Lane {
42 jobs: Some(jobs),
43 done,
44 handle: Some(handle),
45 }
46 })
47 .collect();
48 BandPool { lanes }
49 }
50
51 /// Queue `job` on worker `lane`.
52 pub(super) fn submit(&self, lane: usize, job: J) {
53 let jobs = self.lanes[lane]
54 .jobs
55 .as_ref()
56 .expect("a band worker is running");
57 jobs.send(job).expect("a band worker panicked");
58 }
59
60 /// Wait for worker `lane` to answer its oldest job.
61 pub(super) fn collect(&self, lane: usize) -> R {
62 self.lanes[lane]
63 .done
64 .recv()
65 .expect("a band worker panicked")
66 }
67}
68
69impl<J: Send + 'static, R: Send + 'static> Drop for BandPool<J, R> {
70 fn drop(&mut self) {
71 for lane in &mut self.lanes {
72 drop(lane.jobs.take());
73 }
74 for lane in &mut self.lanes {
75 if let Some(handle) = lane.handle.take() {
76 // A worker that panicked has already reported it; nothing to add.
77 let _ = handle.join();
78 }
79 }
80 }
81}