Skip to main content

paralight/threads/
mod.rs

1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Thread pool implementations.
10
11#[cfg(feature = "rayon")]
12mod rayon;
13#[cfg(feature = "default-thread-pool")]
14mod thread_pool;
15
16#[cfg(feature = "rayon")]
17pub use rayon::RayonThreadPool;
18use std::num::NonZeroUsize;
19#[cfg(feature = "default-thread-pool")]
20pub use thread_pool::{CpuPinningPolicy, ThreadPool, ThreadPoolBuilder};
21
22/// Number of threads to spawn in a thread pool.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum ThreadCount {
25    /// Spawn the number of threads returned by
26    /// [`std::thread::available_parallelism()`].
27    AvailableParallelism,
28    /// Spawn the given number of threads.
29    Count(NonZeroUsize),
30}
31
32impl ThreadCount {
33    /// Resolves the number of threads to spawn.
34    pub fn count(self) -> NonZeroUsize {
35        match self {
36            ThreadCount::AvailableParallelism => std::thread::available_parallelism()
37                .expect("Getting the available parallelism failed"),
38            ThreadCount::Count(count) => count,
39        }
40    }
41}
42
43impl TryFrom<usize> for ThreadCount {
44    type Error = <NonZeroUsize as TryFrom<usize>>::Error;
45
46    fn try_from(thread_count: usize) -> Result<Self, Self::Error> {
47        let count = NonZeroUsize::try_from(thread_count)?;
48        Ok(ThreadCount::Count(count))
49    }
50}
51
52/// Strategy to distribute ranges of work items among threads.
53#[derive(Clone, Copy)]
54pub enum RangeStrategy {
55    /// Each thread processes a fixed range of items.
56    Fixed,
57    /// Threads can steal work from each other.
58    WorkStealing,
59}
60
61#[cfg(test)]
62mod test {
63    use super::*;
64
65    #[test]
66    fn test_thread_count_try_from_usize() {
67        assert!(ThreadCount::try_from(0).is_err());
68        assert_eq!(
69            ThreadCount::try_from(1),
70            Ok(ThreadCount::Count(NonZeroUsize::try_from(1).unwrap()))
71        );
72    }
73}