Skip to main content

euv_core/parallel/
impl.rs

1use super::*;
2
3/// Cache-line-isolated atomic counter helpers for `AlignedAtomicUsize`.
4impl AlignedAtomicUsize {
5    /// Creates a new cache-line-aligned atomic counter initialized to `initial`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Initial atomic value.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Initialized aligned atomic counter.
14    #[cfg_attr(not(target_arch = "wasm32"), inline)]
15    #[must_use]
16    pub fn new(initial: usize) -> Self {
17        Self {
18            value: AtomicUsize::new(initial),
19        }
20    }
21
22    /// Loads the underlying atomic value with `ordering`.
23    ///
24    /// # Arguments
25    ///
26    /// - `Ordering` - Memory ordering constraint.
27    ///
28    /// # Returns
29    ///
30    /// - `usize` - Loaded value.
31    #[cfg_attr(not(target_arch = "wasm32"), inline)]
32    #[must_use]
33    pub fn load(&self, ordering: Ordering) -> usize {
34        let Self { value } = self;
35        value.load(ordering)
36    }
37
38    /// Stores `next_value` into the underlying atomic counter with `ordering`.
39    ///
40    /// # Arguments
41    ///
42    /// - `usize` - Value to store.
43    /// - `Ordering` - Memory ordering constraint.
44    #[cfg_attr(not(target_arch = "wasm32"), inline)]
45    pub fn store(&self, next_value: usize, ordering: Ordering) {
46        let Self { value } = self;
47        value.store(next_value, ordering);
48    }
49
50    /// Atomically adds `delta` and returns the previous value using `ordering`.
51    ///
52    /// # Arguments
53    ///
54    /// - `usize` - Increment delta.
55    /// - `Ordering` - Memory ordering constraint.
56    ///
57    /// # Returns
58    ///
59    /// - `usize` - Previous atomic value before addition.
60    #[cfg_attr(not(target_arch = "wasm32"), inline)]
61    pub fn fetch_add(&self, delta: usize, ordering: Ordering) -> usize {
62        let Self { value } = self;
63        value.fetch_add(delta, ordering)
64    }
65}
66
67/// Unified persistent work-stealing thread pool operations for `EngineWorkerPool`.
68impl EngineWorkerPool {
69    /// Creates a new persistent worker pool sized to the host hardware concurrency (`1..=ENGINE_WORKER_MAX_THREADS`).
70    ///
71    /// # Returns
72    ///
73    /// - `Self` - Initialized worker pool with warm background threads.
74    #[must_use]
75    pub fn new() -> Self {
76        #[cfg(not(target_arch = "wasm32"))]
77        {
78            let total_threads: usize = available_parallelism()
79                .map(usize::from)
80                .unwrap_or(4)
81                .clamp(1, ENGINE_WORKER_MAX_THREADS);
82            Self::with_total_threads(total_threads)
83        }
84        #[cfg(target_arch = "wasm32")]
85        {
86            Self { worker_count: 0 }
87        }
88    }
89
90    /// Creates a persistent worker pool configured for `total_threads` concurrent execution lanes (caller plus background workers).
91    ///
92    /// # Arguments
93    ///
94    /// - `usize` - Desired total thread count clamped to `1..=ENGINE_WORKER_MAX_THREADS`.
95    ///
96    /// # Returns
97    ///
98    /// - `Self` - Initialized worker pool.
99    #[must_use]
100    pub fn with_total_threads(total_threads: usize) -> Self {
101        #[cfg(not(target_arch = "wasm32"))]
102        {
103            let clamped_total: usize = total_threads.clamp(1, ENGINE_WORKER_MAX_THREADS);
104            let requested_workers: usize = clamped_total.saturating_sub(1);
105            let mut slots: Vec<EngineWorkerSlot> = Vec::with_capacity(requested_workers);
106            for _ in 0..requested_workers {
107                slots.push(EngineWorkerSlot::default());
108            }
109            let shared: Arc<EnginePoolShared> = Arc::new(EnginePoolShared {
110                active_job: AtomicUsize::new(0),
111                active_workers: AtomicUsize::new(0),
112                spin_limit: AtomicUsize::new(ENGINE_ACTIVE_SPIN_LIMIT.load(Ordering::Relaxed)),
113                shutdown: AtomicUsize::new(0),
114                caller_parked: AlignedAtomicUsize::default(),
115                caller_lock: Mutex::new(()),
116                wake_caller: Condvar::new(),
117                slots,
118            });
119            let mut handles: Vec<JoinHandle<()>> = Vec::with_capacity(requested_workers);
120            for worker_slot_idx in 0..requested_workers {
121                let shared_clone: Arc<EnginePoolShared> = Arc::clone(&shared);
122                let thread_name: String =
123                    format!("{ENGINE_WORKER_THREAD_PREFIX}-{worker_slot_idx}");
124                let worker_lane_id: usize = worker_slot_idx.saturating_add(1);
125                if let Ok(handle) = Builder::new().name(thread_name).spawn(move || {
126                    engine_worker_thread_loop(&shared_clone, worker_slot_idx, worker_lane_id);
127                }) {
128                    handles.push(handle);
129                } else {
130                    break;
131                }
132            }
133            let worker_count: usize = handles.len();
134            Self {
135                worker_count,
136                dispatch_guard: Mutex::new(()),
137                shared,
138                handles,
139            }
140        }
141        #[cfg(target_arch = "wasm32")]
142        {
143            let _: usize = total_threads;
144            Self { worker_count: 0 }
145        }
146    }
147
148    /// Returns the count of active background worker threads excluding the calling thread.
149    ///
150    /// # Returns
151    ///
152    /// - `usize` - Background worker thread count (`0` on single-core or `wasm32`).
153    #[cfg_attr(not(target_arch = "wasm32"), inline)]
154    #[must_use]
155    pub fn worker_count(&self) -> usize {
156        let Self { worker_count, .. } = self;
157        *worker_count
158    }
159
160    /// Returns total concurrent execution threads including the calling thread (`1..=ENGINE_WORKER_MAX_THREADS`).
161    ///
162    /// # Returns
163    ///
164    /// - `usize` - Total execution thread count.
165    #[cfg_attr(not(target_arch = "wasm32"), inline)]
166    #[must_use]
167    pub fn total_threads(&self) -> usize {
168        self.worker_count().saturating_add(1)
169    }
170
171    /// Updates the adaptive hybrid spin limit on this pool (`ENGINE_WORKER_SPIN_LIMIT_ACTIVE` vs `ENGINE_WORKER_SPIN_LIMIT_IDLE`).
172    ///
173    /// # Arguments
174    ///
175    /// - `bool` - `true` when high-frequency frames are active; `false` for immediate idle parking.
176    pub fn set_spin_active(&self, active: bool) {
177        #[cfg(not(target_arch = "wasm32"))]
178        {
179            let limit: usize = if active {
180                ENGINE_WORKER_SPIN_LIMIT_ACTIVE as usize
181            } else {
182                ENGINE_WORKER_SPIN_LIMIT_IDLE as usize
183            };
184            let Self { shared, .. } = self;
185            shared.spin_limit.store(limit, Ordering::Relaxed);
186        }
187        #[cfg(target_arch = "wasm32")]
188        {
189            let _: bool = active;
190        }
191    }
192
193    /// Returns the active adaptive spin-loop iteration limit configured on this pool.
194    ///
195    /// # Returns
196    ///
197    /// - `u32` - Active spin iteration count.
198    #[must_use]
199    pub fn spin_limit(&self) -> u32 {
200        #[cfg(not(target_arch = "wasm32"))]
201        {
202            let Self { shared, .. } = self;
203            shared.spin_limit.load(Ordering::Relaxed) as u32
204        }
205        #[cfg(target_arch = "wasm32")]
206        {
207            0
208        }
209    }
210
211    /// Dispatches a type-erased stack-pinned raw job across up to `max_workers` background threads plus the calling thread.
212    ///
213    /// # Arguments
214    ///
215    /// - `usize` - Stack-pinned payload pointer valid until all workers complete.
216    /// - `unsafe fn(usize, usize)` - Trampoline receiving `(payload_ptr, worker_lane_index)` (`0` = caller, `1..=max_workers` = workers).
217    /// - `usize` - Maximum number of background workers to wake for this epoch.
218    #[cfg(not(target_arch = "wasm32"))]
219    pub(crate) fn dispatch_raw(
220        &self,
221        payload_ptr: usize,
222        invoke: unsafe fn(usize, usize),
223        max_workers: usize,
224    ) {
225        let Self {
226            worker_count,
227            dispatch_guard,
228            shared,
229            ..
230        } = self;
231        let dispatch_workers: usize = (*worker_count).min(max_workers);
232        if dispatch_workers == 0 {
233            // SAFETY: Caller guarantees `payload_ptr` is valid for `invoke`.
234            unsafe {
235                invoke(payload_ptr, 0);
236            }
237            return;
238        }
239        let Ok(_guard) = dispatch_guard.try_lock() else {
240            // SAFETY: Re-entrant caller falls back serially while `payload_ptr` is live on stack.
241            unsafe {
242                invoke(payload_ptr, 0);
243            }
244            return;
245        };
246        let job: EngineDispatchJob = EngineDispatchJob {
247            payload_ptr,
248            invoke,
249            workers_done: AlignedAtomicUsize::default(),
250        };
251        shared
252            .active_workers
253            .store(dispatch_workers, Ordering::Relaxed);
254        shared.active_job.store(
255            (&job as *const EngineDispatchJob) as usize,
256            Ordering::Release,
257        );
258        let active_slots: &[EngineWorkerSlot] = &shared.slots[..dispatch_workers];
259        for slot in active_slots.iter() {
260            let next_epoch: usize = slot.epoch.load(Ordering::Relaxed).wrapping_add(1);
261            slot.epoch.store(next_epoch, Ordering::SeqCst);
262        }
263        for slot in active_slots.iter() {
264            if slot.parked.load(Ordering::SeqCst) != 0
265                && let Ok(_slot_guard) = slot.lock.lock()
266            {
267                slot.wake.notify_one();
268            }
269        }
270        // SAFETY: Caller executes lane `0` while `job` and `payload_ptr` remain stack-pinned.
271        unsafe {
272            invoke(payload_ptr, 0);
273        }
274        let caller_spin_limit: u32 = if shared.spin_limit.load(Ordering::Relaxed) > 0 {
275            ENGINE_CALLER_SPIN_LIMIT_ACTIVE
276        } else {
277            ENGINE_CALLER_SPIN_LIMIT_IDLE
278        };
279        let mut caller_spins: u32 = 0;
280        while job.workers_done.load(Ordering::Acquire) < dispatch_workers {
281            if caller_spins < caller_spin_limit {
282                caller_spins = caller_spins.saturating_add(1);
283                spin_loop();
284                continue;
285            }
286            if let Ok(mut guard) = shared.caller_lock.lock() {
287                shared.caller_parked.store(1, Ordering::SeqCst);
288                while job.workers_done.load(Ordering::SeqCst) < dispatch_workers {
289                    let Ok(next_guard) = shared.wake_caller.wait(guard) else {
290                        break;
291                    };
292                    guard = next_guard;
293                }
294                shared.caller_parked.store(0, Ordering::SeqCst);
295            } else {
296                spin_loop();
297            }
298        }
299        shared.active_job.store(0, Ordering::Release);
300    }
301
302    /// Partitions `[0..total_items)` into `grain_size` chunks claimed lock-free across workers and executes `work_fn(start, end, worker_lane)`.
303    ///
304    /// # Arguments
305    ///
306    /// - `usize` - Total number of logical items to process.
307    /// - `usize` - Minimum items per claimed work-stealing chunk (`>= 1`).
308    /// - `WorkFn` - Synchronized closure receiving `(chunk_start, chunk_end, worker_lane_index)`.
309    pub fn parallel_for_chunks<WorkFn>(
310        &self,
311        total_items: usize,
312        grain_size: usize,
313        work_fn: WorkFn,
314    ) where
315        WorkFn: Fn(usize, usize, usize) + Sync,
316    {
317        if total_items == 0 {
318            return;
319        }
320        let effective_grain: usize = grain_size.max(1);
321        let chunk_count: usize = total_items.div_ceil(effective_grain);
322        if chunk_count <= 1 || self.worker_count() == 0 {
323            work_fn(0, total_items, 0);
324            return;
325        }
326        #[cfg(not(target_arch = "wasm32"))]
327        {
328            let state: ParallelChunksState<'_, WorkFn> = ParallelChunksState {
329                total_items,
330                grain_size: effective_grain,
331                chunk_count,
332                next_chunk: AlignedAtomicUsize::default(),
333                work_fn: &work_fn,
334            };
335            let max_workers: usize = chunk_count.saturating_sub(1);
336            let payload_ptr: usize = (&state as *const ParallelChunksState<'_, WorkFn>) as usize;
337            self.dispatch_raw(
338                payload_ptr,
339                parallel_chunks_trampoline::<WorkFn>,
340                max_workers,
341            );
342        }
343        #[cfg(target_arch = "wasm32")]
344        {
345            work_fn(0, total_items, 0);
346        }
347    }
348
349    /// Executes `work_fn(index, item, worker_lane)` for every element in `items` using lock-free atomic work-stealing.
350    ///
351    /// # Arguments
352    ///
353    /// - `&[ItemType]` - Contiguous slice of work items to distribute across workers.
354    /// - `WorkFn` - Synchronized closure receiving `(item_index, item_ref, worker_lane_index)`.
355    pub fn parallel_work_steal<ItemType, WorkFn>(&self, items: &[ItemType], work_fn: WorkFn)
356    where
357        ItemType: Sync,
358        WorkFn: Fn(usize, &ItemType, usize) + Sync,
359    {
360        if items.is_empty() {
361            return;
362        }
363        if items.len() == 1 || self.worker_count() == 0 {
364            for (item_index, item_ref) in items.iter().enumerate() {
365                work_fn(item_index, item_ref, 0);
366            }
367            return;
368        }
369        #[cfg(not(target_arch = "wasm32"))]
370        {
371            let state: ParallelStealState<'_, ItemType, WorkFn> = ParallelStealState {
372                items,
373                next_index: AlignedAtomicUsize::default(),
374                work_fn: &work_fn,
375            };
376            let max_workers: usize = items.len().saturating_sub(1);
377            let payload_ptr: usize =
378                (&state as *const ParallelStealState<'_, ItemType, WorkFn>) as usize;
379            self.dispatch_raw(
380                payload_ptr,
381                parallel_steal_trampoline::<ItemType, WorkFn>,
382                max_workers,
383            );
384        }
385        #[cfg(target_arch = "wasm32")]
386        {
387            for (item_index, item_ref) in items.iter().enumerate() {
388                work_fn(item_index, item_ref, 0);
389            }
390        }
391    }
392}
393
394/// Default construction creating a host-sized `EngineWorkerPool`.
395impl Default for EngineWorkerPool {
396    /// Creates a default host-sized `EngineWorkerPool`.
397    ///
398    /// # Returns
399    ///
400    /// - `Self` - Host-sized persistent worker pool.
401    fn default() -> Self {
402        Self::new()
403    }
404}
405
406/// Clean background thread shutdown and handle join when an `EngineWorkerPool` drops.
407#[cfg(not(target_arch = "wasm32"))]
408impl Drop for EngineWorkerPool {
409    /// Signals all persistent background worker threads to exit and joins every handle.
410    fn drop(&mut self) {
411        let Self {
412            shared, handles, ..
413        } = self;
414        shared.shutdown.store(1, Ordering::SeqCst);
415        for slot in shared.slots.iter() {
416            if let Ok(_guard) = slot.lock.lock() {
417                slot.wake.notify_one();
418            }
419        }
420        for handle in handles.drain(..) {
421            let _: Result<(), Box<dyn Any + Send>> = handle.join();
422        }
423    }
424}