1use crate::LockExt;
13use std::cell::Cell;
14use std::collections::HashMap;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::{Arc, Mutex, OnceLock};
17
18thread_local! {
19 static SEQUENTIAL: Cell<bool> = const { Cell::new(false) };
20}
21
22const NO_THREADS: bool = cfg!(all(target_arch = "wasm32", not(target_feature = "atomics")));
24
25#[cfg(all(target_arch = "wasm32", target_feature = "atomics"))]
28static POOL_READY: AtomicBool = AtomicBool::new(false);
29
30#[cfg(all(target_arch = "wasm32", target_feature = "atomics"))]
32pub fn set_pool_ready() {
33 POOL_READY.store(true, Ordering::Relaxed);
34}
35
36fn no_threads() -> bool {
37 #[cfg(all(target_arch = "wasm32", target_feature = "atomics"))]
38 if !POOL_READY.load(Ordering::Relaxed) {
39 return true;
40 }
41 NO_THREADS
42}
43
44pub fn sequential() -> bool {
46 no_threads() || SEQUENTIAL.with(|c| c.get())
47}
48
49fn pool(n: usize, apart: bool) -> Result<Arc<rayon::ThreadPool>, rayon::ThreadPoolBuildError> {
53 type Pools = HashMap<(usize, bool), Arc<rayon::ThreadPool>>;
54 static POOLS: OnceLock<Mutex<Pools>> = OnceLock::new();
55 let mut m = POOLS.get_or_init(Default::default).lock_ok();
56 if let Some(p) = m.get(&(n, apart)) {
57 return Ok(p.clone());
58 }
59 let p = Arc::new(rayon::ThreadPoolBuilder::new().num_threads(n).build()?);
60 m.insert((n, apart), p.clone());
61 Ok(p)
62}
63
64pub fn with_threads<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> R {
70 threads_in(threads, false, f)
71}
72
73pub fn with_threads_apart<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> R {
76 threads_in(threads, true, f)
77}
78
79fn threads_in<R: Send>(threads: Option<usize>, apart: bool, f: impl FnOnce() -> R + Send) -> R {
80 match threads {
81 None if sequential() => f(),
83 None if rayon::current_thread_index().is_none() && default_threads().is_some() => {
85 threads_in(default_threads(), apart, f)
86 }
87 None | Some(0) => with_flag(false, f),
88 Some(1) => with_flag(true, f),
89 Some(_) if cfg!(target_arch = "wasm32") => with_flag(false, f),
91 Some(n) => match pool(n, apart) {
92 Ok(p) => {
93 let c = current();
95 p.install(move || with_ctx(&c, f))
96 }
97 Err(_) => with_flag(true, f),
99 },
100 }
101}
102
103static DEFAULT_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
105
106pub(crate) fn set_default_threads(n: Option<usize>) {
109 DEFAULT_THREADS.store(n.unwrap_or(0), Ordering::Relaxed);
110}
111
112pub fn default_threads() -> Option<usize> {
114 Some(DEFAULT_THREADS.load(Ordering::Relaxed)).filter(|&n| n > 0)
115}
116
117pub(crate) fn default_threads_from_env() {
120 let n = std::env::var("LENSBENCH_THREADS")
121 .ok()
122 .and_then(|s| s.trim().parse::<usize>().ok());
123 set_default_threads(n);
124}
125
126fn with_flag<R>(seq: bool, f: impl FnOnce() -> R) -> R {
128 struct Restore(bool);
129 impl Drop for Restore {
130 fn drop(&mut self) {
131 SEQUENTIAL.with(|c| c.set(self.0));
132 }
133 }
134 let _g = Restore(SEQUENTIAL.with(|c| c.replace(seq)));
135 f()
136}
137
138pub fn current_threads() -> usize {
140 if sequential() {
141 1
142 } else {
143 rayon::current_num_threads()
144 }
145}
146
147#[doc(hidden)]
150pub fn for_each_chunk_mut<T: Send>(
151 a: &mut [T],
152 n: usize,
153 f: impl Fn(usize, &mut [T]) + Sync + Send,
154) {
155 use rayon::prelude::*;
156 if sequential() {
157 a.chunks_mut(n).enumerate().for_each(|(i, c)| f(i, c));
158 } else {
159 let cx = current();
160 a.par_chunks_mut(n)
161 .enumerate()
162 .for_each(|(i, c)| with_ctx(&cx, || f(i, c)));
163 }
164}
165
166pub fn map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync + Send) -> Vec<R> {
169 use rayon::prelude::*;
170 if sequential() || items.len() < 2 {
171 items.iter().map(f).collect()
172 } else {
173 items.par_iter().with_max_len(1).map(scoped(f)).collect()
174 }
175}
176
177pub fn try_map<T: Sync, R: Send, E: Send>(
180 items: &[T],
181 f: impl Fn(&T) -> Result<R, E> + Sync + Send,
182) -> Result<Vec<R>, E> {
183 let failed = AtomicBool::new(false);
184 let out = map(items, |x| {
185 if failed.load(Ordering::Relaxed) {
186 return None;
187 }
188 let r = f(x);
189 if r.is_err() {
190 failed.store(true, Ordering::Relaxed);
191 }
192 Some(r)
193 });
194 let mut v = Vec::with_capacity(out.len());
195 let mut skipped = false;
196 for r in out {
197 match r {
198 Some(Ok(x)) => v.push(x),
199 Some(Err(e)) => return Err(e),
200 None => skipped = true,
201 }
202 }
203 debug_assert!(!skipped, "skipped only after an error");
204 Ok(v)
205}
206
207#[derive(Clone, Debug, Default)]
211pub struct CancelToken {
212 flag: Arc<AtomicBool>,
213 parent: Option<Arc<CancelToken>>,
214}
215
216impl CancelToken {
217 pub fn new() -> Self {
218 Self::default()
219 }
220
221 pub fn child(&self) -> Self {
223 Self {
224 flag: Arc::default(),
225 parent: Some(Arc::new(self.clone())),
226 }
227 }
228
229 pub fn cancel(&self) {
231 self.flag.store(true, Ordering::Relaxed);
232 }
233
234 pub fn is_cancelled(&self) -> bool {
236 self.flag.load(Ordering::Relaxed) || self.parent.as_ref().is_some_and(|p| p.is_cancelled())
237 }
238
239 pub fn same(&self, o: &CancelToken) -> bool {
241 Arc::ptr_eq(&self.flag, &o.flag)
242 }
243}
244
245#[derive(Clone, Debug, PartialEq)]
247pub enum Event {
248 Iter(Iter),
250 Count(Count),
252}
253
254#[derive(Clone, Debug, PartialEq)]
256pub struct Iter {
257 pub iter: usize,
259 pub merit: f64,
261 pub x: Vec<f64>,
263 pub damping: f64,
265 pub evals: usize,
267}
268
269#[derive(Clone, Copy, Debug, PartialEq)]
271pub struct Count {
272 pub stage: &'static str,
274 pub done: usize,
276 pub total: usize,
277 pub ran: usize,
279 pub elapsed: f64,
281 pub eta: Option<f64>,
283}
284
285pub type ProgressFn = Arc<dyn Fn(&Event) + Send + Sync>;
287
288#[derive(Clone, Default)]
290pub struct Ctx {
291 pub cancel: Option<CancelToken>,
293 pub no_batch: bool,
295 pub ext: Option<Arc<crate::ext::Ext>>,
297 pub fs: Option<Arc<dyn crate::vfs::Fs>>,
299 pub progress: Option<ProgressFn>,
301}
302
303impl std::fmt::Debug for Ctx {
304 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305 f.debug_struct("Ctx")
306 .field("cancel", &self.cancel)
307 .field("no_batch", &self.no_batch)
308 .field("ext", &self.ext)
309 .field("fs", &self.fs.as_ref().map(|_| "..."))
310 .field("progress", &self.progress.as_ref().map(|_| "..."))
311 .finish()
312 }
313}
314
315thread_local! {
316 static CTX: std::cell::RefCell<Ctx> = std::cell::RefCell::new(Ctx::default());
318}
319
320pub fn with_ctx<R>(c: &Ctx, f: impl FnOnce() -> R) -> R {
322 struct Restore(Option<Ctx>);
323 impl Drop for Restore {
324 fn drop(&mut self) {
325 if let Some(c) = self.0.take() {
326 CTX.with(|x| *x.borrow_mut() = c);
327 }
328 }
329 }
330 let _g = Restore(Some(CTX.with(|x| x.replace(c.clone()))));
331 f()
332}
333
334pub fn current() -> Ctx {
336 CTX.with(|x| x.borrow().clone())
337}
338
339pub fn with_cancel<R>(t: Option<&CancelToken>, f: impl FnOnce() -> R) -> R {
341 let c = Ctx {
342 cancel: t.cloned(),
343 ..current()
344 };
345 with_ctx(&c, f)
346}
347
348pub fn with_progress<R>(p: Option<ProgressFn>, f: impl FnOnce() -> R) -> R {
351 let c = Ctx {
352 progress: p,
353 ..current()
354 };
355 with_ctx(&c, f)
356}
357
358pub fn report(e: &Event) {
360 let p = CTX.with(|x| x.borrow().progress.clone());
361 if let Some(p) = p {
362 p(e);
363 }
364}
365
366pub fn reporting() -> bool {
368 CTX.with(|x| x.borrow().progress.is_some())
369}
370
371pub fn with_batch<R>(on: bool, f: impl FnOnce() -> R) -> R {
373 let c = Ctx {
374 no_batch: !on,
375 ..current()
376 };
377 with_ctx(&c, f)
378}
379
380pub(crate) fn with_ext<R>(e: Arc<crate::ext::Ext>, f: impl FnOnce() -> R) -> R {
382 let c = Ctx {
383 ext: Some(e),
384 ..current()
385 };
386 with_ctx(&c, f)
387}
388
389pub(crate) fn current_ext() -> Option<Arc<crate::ext::Ext>> {
391 CTX.with(|x| x.borrow().ext.clone())
392}
393
394pub(crate) fn with_fs<R>(fs: Arc<dyn crate::vfs::Fs>, f: impl FnOnce() -> R) -> R {
396 let c = Ctx {
397 fs: Some(fs),
398 ..current()
399 };
400 with_ctx(&c, f)
401}
402
403pub(crate) fn current_fs() -> Option<Arc<dyn crate::vfs::Fs>> {
405 CTX.with(|x| x.borrow().fs.clone())
406}
407
408pub(crate) fn batch_enabled() -> bool {
410 CTX.with(|x| !x.borrow().no_batch)
411}
412
413pub fn scoped<A, R>(f: impl Fn(A) -> R + Sync + Send) -> impl Fn(A) -> R + Sync + Send {
415 let c = current();
416 move |a| with_ctx(&c, || f(a))
417}
418
419pub fn current_cancel() -> Option<CancelToken> {
421 CTX.with(|x| x.borrow().cancel.clone())
422}
423
424pub fn cancelled() -> bool {
426 CTX.with(|x| {
427 x.borrow()
428 .cancel
429 .as_ref()
430 .is_some_and(CancelToken::is_cancelled)
431 })
432}
433
434pub fn check_cancel() -> crate::Result<()> {
436 if cancelled() {
437 Err(crate::error::Error::Cancelled)
438 } else {
439 Ok(())
440 }
441}
442
443#[cfg(test)]
444mod cancel_tests {
445 use super::*;
446
447 #[test]
449 fn token_is_per_computation_and_reaches_workers() {
450 let a = CancelToken::new();
451 let b = CancelToken::new();
452 a.cancel();
453 with_cancel(Some(&a), || {
454 assert!(check_cancel().is_err());
455 let v = with_threads(Some(3), || map(&[1, 2, 3, 4], |_| cancelled()));
456 assert!(v.iter().all(|&x| x));
457 });
458 with_cancel(Some(&b), || {
459 assert!(check_cancel().is_ok());
460 let v = with_threads(Some(3), || map(&[1, 2, 3, 4], |_| cancelled()));
461 assert!(v.iter().all(|&x| !x));
462 });
463 assert!(!cancelled());
465 }
466
467 #[test]
469 fn child_token_and_progress() {
470 let a = CancelToken::new();
471 let c = a.child();
472 assert!(!c.is_cancelled());
473 c.cancel();
474 assert!(c.is_cancelled() && !a.is_cancelled());
475 let c2 = a.child();
476 a.cancel();
477 assert!(c2.is_cancelled());
478 let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));
479 let n2 = n.clone();
480 let p: ProgressFn = Arc::new(move |_| {
481 n2.fetch_add(1, Ordering::Relaxed);
482 });
483 with_progress(Some(p), || {
484 with_threads(Some(3), || {
485 map(&[1, 2, 3, 4], |_| {
486 report(&Event::Count(Count {
487 stage: "",
488 done: 1,
489 total: 4,
490 ran: 1,
491 elapsed: 0.0,
492 eta: None,
493 }))
494 })
495 })
496 });
497 assert_eq!(n.load(Ordering::Relaxed), 4);
498 assert!(!reporting());
499 }
500
501 #[test]
503 fn try_map_order_and_error() {
504 let v: Vec<usize> = (0..50).collect();
505 let r = with_threads(Some(3), || try_map(&v, |&x| Ok::<_, String>(x * 2)));
506 assert_eq!(r.unwrap(), (0..50).map(|x| x * 2).collect::<Vec<_>>());
507 let r = with_threads(Some(3), || {
508 try_map(&v, |&x| if x == 7 { Err(x) } else { Ok(x) })
509 });
510 assert_eq!(r, Err(7));
511 }
512
513 #[test]
515 fn batch_switch_is_scoped() {
516 assert!(batch_enabled());
517 let v = with_batch(false, || {
518 with_threads(Some(3), || map(&[1, 2, 3, 4], |_| batch_enabled()))
519 });
520 assert!(v.iter().all(|&x| !x));
521 assert!(batch_enabled());
522 }
523}