bp3d_threads/thread_pool/
scoped.rs

1// Copyright (c) 2021, BlockProject 3D
2//
3// All rights reserved.
4//
5// Redistribution and use in source and binary forms, with or without modification,
6// are permitted provided that the following conditions are met:
7//
8//     * Redistributions of source code must retain the above copyright notice,
9//       this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above copyright notice,
11//       this list of conditions and the following disclaimer in the documentation
12//       and/or other materials provided with the distribution.
13//     * Neither the name of BlockProject 3D nor the names of its contributors
14//       may be used to endorse or promote products derived from this software
15//       without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29use super::core::ThreadManager;
30use crate::Join;
31use crossbeam::thread::{Scope, ScopedJoinHandle};
32
33impl<'a> Join for ScopedJoinHandle<'a, ()> {
34    fn join(self) -> std::thread::Result<()> {
35        self.join()
36    }
37}
38
39/// Represents a ScopedThreadManager (to use with crossbeam::scope).
40pub struct ScopedThreadManager<'env, 'scope>(&'env Scope<'scope>);
41
42impl<'env, 'scope: 'env> ThreadManager<'scope> for ScopedThreadManager<'env, 'scope> {
43    type Handle = ScopedJoinHandle<'env, ()>;
44
45    fn spawn_thread<F: FnOnce() + Send + 'scope>(&self, func: F) -> Self::Handle {
46        self.0.spawn(|_| func())
47    }
48}
49
50impl<'env, 'scope> ScopedThreadManager<'env, 'scope> {
51    /// Creates new ScopedThreadManager.
52    ///
53    /// # Arguments
54    ///
55    /// * `scope`: the [Scope](crossbeam::thread::Scope) to use.
56    ///
57    /// returns: ScopedThreadManager
58    ///
59    /// # Examples
60    ///
61    /// ```
62    /// use bp3d_threads::ThreadPool;
63    /// use bp3d_threads::ScopedThreadManager;
64    /// crossbeam::scope(|scope| {
65    ///     let manager = ScopedThreadManager::new(scope);
66    ///     let mut pool: ThreadPool<ScopedThreadManager, i32> = ThreadPool::new(4);
67    ///     assert!(pool.is_idle());
68    ///     pool.send(&manager, |_| 12);
69    ///     assert!(!pool.is_idle());
70    ///     pool.wait().unwrap();
71    ///     assert!(pool.is_idle());
72    /// }).unwrap();
73    /// ```
74    pub fn new(scope: &'env Scope<'scope>) -> Self {
75        Self(scope)
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use crate::thread_pool::{ScopedThreadManager, ThreadPool};
82    use std::ops::Deref;
83
84    fn fibonacci_recursive(n: usize) -> usize {
85        if n == 0 {
86            0
87        } else if n == 1 {
88            1
89        } else {
90            fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
91        }
92    }
93
94    #[test]
95    fn basic() {
96        const N: usize = 50;
97        let mystr = String::from("This is a test");
98        let s = mystr.deref();
99        let mut tasks = 0;
100        crossbeam::scope(|scope| {
101            let manager = ScopedThreadManager::new(scope);
102            let mut pool: ThreadPool<ScopedThreadManager, usize> = ThreadPool::new(4);
103            for _ in 0..N - 1 {
104                pool.send(&manager, |_| fibonacci_recursive(20));
105            }
106            pool.send(&manager, |_| {
107                if s == "This is a test" {
108                    fibonacci_recursive(20)
109                } else {
110                    0
111                }
112            });
113            assert!(!pool.is_idle());
114            pool.wait().unwrap();
115            assert!(pool.is_idle());
116            while let Some(event) = pool.poll() {
117                assert_eq!(event, 6765);
118                tasks += 1;
119            }
120        })
121        .unwrap();
122        assert_eq!(tasks, N);
123    }
124}