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
use std::future::Future;
#[cfg(feature = "built-in-executor")]
use {async_executor::Executor as AsyncExecutor, async_io::block_on, once_cell::sync::Lazy};
pub trait Executor: Send + Sync {
fn spawn<T: Send + 'static>(&self, future: impl Future<Output = T> + Send + 'static);
fn block_on<T>(&self, future: impl Future<Output = T>) -> T;
}
#[cfg(feature = "built-in-executor")]
static BUILTIN_EXECUTOR: Lazy<AsyncExecutor<'_>> = Lazy::new(|| {
let ex = AsyncExecutor::new();
for n in 1..=num_cpus::get() {
std::thread::Builder::new()
.name(format!("amiya-builtin-executor-{}", n))
.spawn(|| loop {
std::panic::catch_unwind(|| {
async_io::block_on(BUILTIN_EXECUTOR.run(std::future::pending::<()>()))
})
.ok();
})
.expect("cannot spawn executor thread");
}
ex
});
#[derive(Debug, Default, Clone)]
pub struct BuiltInExecutor;
#[cfg(feature = "built-in-executor")]
impl Executor for BuiltInExecutor {
fn spawn<T: Send + 'static>(&self, future: impl Future<Output = T> + Send + 'static) {
BUILTIN_EXECUTOR.spawn(future).detach()
}
fn block_on<T>(&self, future: impl Future<Output = T>) -> T {
block_on(BUILTIN_EXECUTOR.run(future))
}
}