Skip to main content

futures_executor/
thread_pool.rs

1use crate::enter;
2use crate::unpark_mutex::UnparkMutex;
3use futures_core::future::Future;
4use futures_core::task::{Context, Poll};
5use futures_task::{waker_ref, ArcWake};
6use futures_task::{FutureObj, Spawn, SpawnError};
7use futures_util::future::FutureExt;
8use std::boxed::Box;
9use std::fmt;
10use std::format;
11use std::io;
12use std::string::String;
13use std::sync::atomic::{AtomicUsize, Ordering};
14use std::sync::mpsc;
15use std::sync::{Arc, Mutex};
16use std::thread;
17
18/// A general-purpose thread pool for scheduling tasks that poll futures to
19/// completion.
20///
21/// The thread pool multiplexes any number of tasks onto a fixed number of
22/// worker threads.
23///
24/// This type is a clonable handle to the threadpool itself.
25/// Cloning it will only create a new reference, not a new threadpool.
26///
27/// This type is only available when the `thread-pool` feature of this
28/// library is activated.
29#[cfg_attr(docsrs, doc(cfg(feature = "thread-pool")))]
30pub struct ThreadPool {
31    state: Arc<PoolState>,
32}
33
34/// Thread pool configuration object.
35///
36/// This type is only available when the `thread-pool` feature of this
37/// library is activated.
38#[cfg_attr(docsrs, doc(cfg(feature = "thread-pool")))]
39pub struct ThreadPoolBuilder {
40    pool_size: usize,
41    stack_size: usize,
42    name_prefix: Option<String>,
43    after_start: Option<Arc<dyn Fn(usize) + Send + Sync>>,
44    before_stop: Option<Arc<dyn Fn(usize) + Send + Sync>>,
45}
46
47#[allow(dead_code)]
48trait AssertSendSync: Send + Sync {}
49impl AssertSendSync for ThreadPool {}
50
51struct PoolState {
52    tx: Mutex<mpsc::Sender<Message>>,
53    rx: Mutex<mpsc::Receiver<Message>>,
54    cnt: AtomicUsize,
55    size: usize,
56}
57
58impl fmt::Debug for ThreadPool {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.debug_struct("ThreadPool").field("size", &self.state.size).finish()
61    }
62}
63
64impl fmt::Debug for ThreadPoolBuilder {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.debug_struct("ThreadPoolBuilder")
67            .field("pool_size", &self.pool_size)
68            .field("name_prefix", &self.name_prefix)
69            .finish()
70    }
71}
72
73enum Message {
74    Run(Task),
75    Close,
76}
77
78impl ThreadPool {
79    /// Creates a new thread pool with the default configuration.
80    ///
81    /// See documentation for the methods in
82    /// [`ThreadPoolBuilder`] for details on the default configuration.
83    pub fn new() -> Result<Self, io::Error> {
84        ThreadPoolBuilder::new().create()
85    }
86
87    /// Create a default thread pool configuration, which can then be customized.
88    ///
89    /// See documentation for the methods in
90    /// [`ThreadPoolBuilder`] for details on the default configuration.
91    pub fn builder() -> ThreadPoolBuilder {
92        ThreadPoolBuilder::new()
93    }
94
95    /// Spawns a future that will be run to completion.
96    ///
97    /// > **Note**: This method is similar to `Spawn::spawn_obj`, except that
98    /// >           it is guaranteed to always succeed.
99    pub fn spawn_obj_ok(&self, future: FutureObj<'static, ()>) {
100        let task = Task {
101            future,
102            wake_handle: Arc::new(WakeHandle { exec: self.clone(), mutex: UnparkMutex::new() }),
103            exec: self.clone(),
104        };
105        self.state.send(Message::Run(task));
106    }
107
108    /// Spawns a task that polls the given future with output `()` to
109    /// completion.
110    ///
111    /// ```
112    /// # {
113    /// use futures::executor::ThreadPool;
114    ///
115    /// let pool = ThreadPool::new().unwrap();
116    ///
117    /// let future = async { /* ... */ };
118    /// pool.spawn_ok(future);
119    /// # }
120    /// # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
121    /// ```
122    ///
123    /// > **Note**: This method is similar to `SpawnExt::spawn`, except that
124    /// >           it is guaranteed to always succeed.
125    pub fn spawn_ok<Fut>(&self, future: Fut)
126    where
127        Fut: Future<Output = ()> + Send + 'static,
128    {
129        self.spawn_obj_ok(FutureObj::new(Box::new(future)))
130    }
131}
132
133impl Spawn for ThreadPool {
134    fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> {
135        self.spawn_obj_ok(future);
136        Ok(())
137    }
138}
139
140impl PoolState {
141    fn send(&self, msg: Message) {
142        self.tx.lock().unwrap().send(msg).unwrap();
143    }
144
145    fn work(
146        &self,
147        idx: usize,
148        after_start: Option<Arc<dyn Fn(usize) + Send + Sync>>,
149        before_stop: Option<Arc<dyn Fn(usize) + Send + Sync>>,
150    ) {
151        let _scope = enter().unwrap();
152        if let Some(after_start) = after_start {
153            after_start(idx);
154        }
155        loop {
156            let msg = self.rx.lock().unwrap().recv().unwrap();
157            match msg {
158                Message::Run(task) => task.run(),
159                Message::Close => break,
160            }
161        }
162        if let Some(before_stop) = before_stop {
163            before_stop(idx);
164        }
165    }
166}
167
168impl Clone for ThreadPool {
169    fn clone(&self) -> Self {
170        self.state.cnt.fetch_add(1, Ordering::Relaxed);
171        Self { state: self.state.clone() }
172    }
173}
174
175impl Drop for ThreadPool {
176    fn drop(&mut self) {
177        if self.state.cnt.fetch_sub(1, Ordering::Relaxed) == 1 {
178            for _ in 0..self.state.size {
179                self.state.send(Message::Close);
180            }
181        }
182    }
183}
184
185impl ThreadPoolBuilder {
186    /// Create a default thread pool configuration.
187    ///
188    /// See the other methods on this type for details on the defaults.
189    pub fn new() -> Self {
190        let pool_size = thread::available_parallelism().map_or(1, |p| p.get());
191        Self { pool_size, stack_size: 0, name_prefix: None, after_start: None, before_stop: None }
192    }
193
194    /// Set size of a future ThreadPool
195    ///
196    /// The size of a thread pool is the number of worker threads spawned. By
197    /// default, this is equal to the number of CPU cores.
198    ///
199    /// # Panics
200    ///
201    /// Panics if `pool_size == 0`.
202    pub fn pool_size(&mut self, size: usize) -> &mut Self {
203        assert!(size > 0);
204        self.pool_size = size;
205        self
206    }
207
208    /// Set stack size of threads in the pool, in bytes.
209    ///
210    /// By default, worker threads use Rust's standard stack size.
211    pub fn stack_size(&mut self, stack_size: usize) -> &mut Self {
212        self.stack_size = stack_size;
213        self
214    }
215
216    /// Set thread name prefix of a future ThreadPool.
217    ///
218    /// Thread name prefix is used for generating thread names. For example, if prefix is
219    /// `my-pool-`, then threads in the pool will get names like `my-pool-1` etc.
220    ///
221    /// By default, worker threads are assigned Rust's standard thread name.
222    pub fn name_prefix<S: Into<String>>(&mut self, name_prefix: S) -> &mut Self {
223        self.name_prefix = Some(name_prefix.into());
224        self
225    }
226
227    /// Execute the closure `f` immediately after each worker thread is started,
228    /// but before running any tasks on it.
229    ///
230    /// This hook is intended for bookkeeping and monitoring.
231    /// The closure `f` will be dropped after the `builder` is dropped
232    /// and all worker threads in the pool have executed it.
233    ///
234    /// The closure provided will receive an index corresponding to the worker
235    /// thread it's running on.
236    pub fn after_start<F>(&mut self, f: F) -> &mut Self
237    where
238        F: Fn(usize) + Send + Sync + 'static,
239    {
240        self.after_start = Some(Arc::new(f));
241        self
242    }
243
244    /// Execute closure `f` just prior to shutting down each worker thread.
245    ///
246    /// This hook is intended for bookkeeping and monitoring.
247    /// The closure `f` will be dropped after the `builder` is dropped
248    /// and all threads in the pool have executed it.
249    ///
250    /// The closure provided will receive an index corresponding to the worker
251    /// thread it's running on.
252    pub fn before_stop<F>(&mut self, f: F) -> &mut Self
253    where
254        F: Fn(usize) + Send + Sync + 'static,
255    {
256        self.before_stop = Some(Arc::new(f));
257        self
258    }
259
260    /// Create a [`ThreadPool`] with the given configuration.
261    pub fn create(&mut self) -> Result<ThreadPool, io::Error> {
262        let (tx, rx) = mpsc::channel();
263        let pool = ThreadPool {
264            state: Arc::new(PoolState {
265                tx: Mutex::new(tx),
266                rx: Mutex::new(rx),
267                cnt: AtomicUsize::new(1),
268                size: self.pool_size,
269            }),
270        };
271
272        for counter in 0..self.pool_size {
273            let state = pool.state.clone();
274            let after_start = self.after_start.clone();
275            let before_stop = self.before_stop.clone();
276            let mut thread_builder = thread::Builder::new();
277            if let Some(ref name_prefix) = self.name_prefix {
278                thread_builder = thread_builder.name(format!("{name_prefix}{counter}"));
279            }
280            if self.stack_size > 0 {
281                thread_builder = thread_builder.stack_size(self.stack_size);
282            }
283            thread_builder.spawn(move || state.work(counter, after_start, before_stop))?;
284        }
285        Ok(pool)
286    }
287}
288
289impl Default for ThreadPoolBuilder {
290    fn default() -> Self {
291        Self::new()
292    }
293}
294
295/// A task responsible for polling a future to completion.
296struct Task {
297    future: FutureObj<'static, ()>,
298    exec: ThreadPool,
299    wake_handle: Arc<WakeHandle>,
300}
301
302struct WakeHandle {
303    mutex: UnparkMutex<Task>,
304    exec: ThreadPool,
305}
306
307impl Task {
308    /// Actually run the task (invoking `poll` on the future) on the current
309    /// thread.
310    fn run(self) {
311        let Self { mut future, wake_handle, mut exec } = self;
312        let waker = waker_ref(&wake_handle);
313        let mut cx = Context::from_waker(&waker);
314
315        // Safety: The ownership of this `Task` object is evidence that
316        // we are in the `POLLING`/`REPOLL` state for the mutex.
317        unsafe {
318            wake_handle.mutex.start_poll();
319
320            loop {
321                let res = future.poll_unpin(&mut cx);
322                match res {
323                    Poll::Pending => {}
324                    Poll::Ready(()) => return wake_handle.mutex.complete(),
325                }
326                let task = Self { future, wake_handle: wake_handle.clone(), exec };
327                match wake_handle.mutex.wait(task) {
328                    Ok(()) => return, // we've waited
329                    Err(task) => {
330                        // someone's notified us
331                        future = task.future;
332                        exec = task.exec;
333                    }
334                }
335            }
336        }
337    }
338}
339
340impl fmt::Debug for Task {
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        f.debug_struct("Task").field("contents", &"...").finish()
343    }
344}
345
346impl ArcWake for WakeHandle {
347    fn wake_by_ref(arc_self: &Arc<Self>) {
348        if let Ok(task) = arc_self.mutex.notify() {
349            arc_self.exec.state.send(Message::Run(task))
350        }
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn test_drop_after_start() {
360        {
361            let (tx, rx) = mpsc::sync_channel(2);
362            let _cpu_pool = ThreadPoolBuilder::new()
363                .pool_size(2)
364                .after_start(move |_| tx.send(1).unwrap())
365                .create()
366                .unwrap();
367
368            // After ThreadPoolBuilder is deconstructed, the tx should be dropped
369            // so that we can use rx as an iterator.
370            let count = rx.into_iter().count();
371            assert_eq!(count, 2);
372        }
373        std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
374    }
375}