1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#![doc(html_root_url = "https://docs.rs/futures-cputask/0.3.0")]
use std::future::Future;
use std::pin::Pin;
use parking_lot::Mutex;
use lazy_static::lazy_static;
mod impls;
pub trait SyncThreadPool {
fn new() -> Self;
fn with_thread_count(num_threads: usize) -> Self;
fn execute<F>(&self, fun: F)
where
F: FnOnce() + Send + 'static;
}
pub trait AsyncThreadPool {
fn new() -> Self;
fn with_thread_count(num_threads: usize) -> Self;
fn execute<F, T>(&self, fun: F) -> Pin<Box<dyn Future<Output = T> + Send + Sync + 'static>>
where
F: FnOnce() -> T + Send + 'static,
T: Sized + Send + Sync + 'static;
}
pub struct ThreadPool<P>
where P: SyncThreadPool + Sized
{
inner: Mutex<P>
}
impl<P> ThreadPool<P>
where P: SyncThreadPool + Sized
{
pub fn from_threadpool(pool: P) -> Self {
Self {
inner: Mutex::new(pool)
}
}
pub fn into_inner(self) -> P {
self.inner.into_inner()
}
}
impl<P> AsyncThreadPool for ThreadPool<P>
where P: SyncThreadPool + Sized
{
fn new() -> Self {
Self::from_threadpool(P::new())
}
fn with_thread_count(num_threads: usize) -> Self {
Self::from_threadpool(P::with_thread_count(num_threads))
}
fn execute<F, T>(&self, fun: F) -> Pin<Box<dyn Future<Output = T> + Send + Sync + 'static>>
where
F: FnOnce() -> T + Send + 'static,
T: Sized + Send + Sync + 'static
{
use futures::prelude::*;
use futures::channel::oneshot::channel;
let (tx, rx) = channel();
self.inner.lock().execute(move || {
let retval = fun();
tx.send(retval).ok();
});
Box::pin(rx.map(|v| v.unwrap()))
}
}
#[cfg(feature = "uvth")]
lazy_static! {
pub static ref GLOBAL_THREADPOOL: ThreadPool<uvth::ThreadPool> = ThreadPool::new();
}
#[cfg(all(feature = "threadpool", not(feature = "uvth")))]
lazy_static! {
pub static ref GLOBAL_THREADPOOL: ThreadPool<threadpool::ThreadPool> = ThreadPool::new();
}
pub fn run_task_in_pool<R, F, T>(fun: F, thread_pool: &T) -> Pin<Box<dyn Future<Output = R> + Send + Sync + 'static>>
where
R: Sized + Send + Sync + 'static,
F: FnOnce() -> R + Send + 'static,
T: AsyncThreadPool
{
thread_pool.execute(fun)
}
#[cfg(any(feature = "uvth", feature = "threadpool"))]
pub fn run_task<R, F>(fun: F) -> Pin<Box<dyn Future<Output = R> + Send + Sync + 'static>>
where
R: Sized + Send + Sync + 'static,
F: FnOnce() -> R + Send + 'static,
{
run_task_in_pool(fun, &*GLOBAL_THREADPOOL)
}
#[cfg(feature = "derive")]
pub use futures_cputask_derive::async_task;