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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use futures_lite::prelude::*;
use once_cell::sync::{Lazy, OnceCell};
use std::{
pin::Pin,
sync::atomic::AtomicUsize,
sync::atomic::{AtomicBool, Ordering},
task::{Context, Poll},
time::{Duration, Instant},
};
mod executor;
mod nursery;
mod sp2c;
pub use executor::*;
pub use nursery::*;
const MONITOR_MS: u64 = 50;
const MAX_THREADS: usize = 500;
static EXEC: Lazy<Executor> = Lazy::new(Executor::new);
static FUTURES_BEING_POLLED: AtomicUsize = AtomicUsize::new(0);
static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
static THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);
static MONITOR: OnceCell<std::thread::JoinHandle<()>> = OnceCell::new();
static SINGLE_THREAD: AtomicBool = AtomicBool::new(false);
pub fn permanently_single_threaded() {
SINGLE_THREAD.store(true, Ordering::Relaxed);
}
fn start_monitor() {
MONITOR.get_or_init(|| {
std::thread::Builder::new()
.name("sscale-mon".into())
.spawn(monitor_loop)
.unwrap()
});
}
fn monitor_loop() {
fn start_thread(exitable: bool, process_io: bool) {
THREAD_COUNT.fetch_add(1, Ordering::Relaxed);
std::thread::Builder::new()
.name(
if exitable {
"sscale-wkr-e"
} else {
"sscale-wkr-c"
}
.into(),
)
.spawn(move || {
let future = async {
scopeguard::defer!({
THREAD_COUNT.fetch_sub(1, Ordering::Relaxed);
});
if exitable {
EXEC.worker()
.run()
.or(async {
async_io::Timer::after(Duration::from_secs(5)).await;
})
.await;
} else {
EXEC.worker().run().await;
};
};
if process_io {
async_io::block_on(future)
} else {
futures_lite::future::block_on(future)
}
})
.unwrap();
}
if SINGLE_THREAD.load(Ordering::Relaxed) {
start_thread(false, true);
return;
} else {
for _ in 0..num_cpus::get() {
start_thread(false, true);
}
}
loop {
EXEC.rebalance();
if SINGLE_THREAD.load(Ordering::Relaxed) {
return;
}
let before_sleep = POLL_COUNT.load(Ordering::Relaxed);
std::thread::sleep(Duration::from_millis(MONITOR_MS));
let after_sleep = POLL_COUNT.load(Ordering::Relaxed);
let running_threads = THREAD_COUNT.load(Ordering::Relaxed);
let full_running = FUTURES_BEING_POLLED.load(Ordering::Relaxed) >= running_threads;
if after_sleep == before_sleep && running_threads <= MAX_THREADS && full_running {
start_thread(true, false);
}
}
}
pub fn block_on<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> T {
futures_lite::future::block_on(spawn(future))
}
pub fn spawn<T: Send + 'static>(
future: impl Future<Output = T> + Send + 'static,
) -> async_executor::Task<T> {
start_monitor();
EXEC.spawn(WrappedFuture::new(future))
}
struct WrappedFuture<T, F: Future<Output = T>> {
fut: F,
}
static ACTIVE_TASKS: AtomicUsize = AtomicUsize::new(0);
pub fn active_task_count() -> usize {
ACTIVE_TASKS.load(Ordering::Relaxed)
}
pub fn running_task_count() -> usize {
FUTURES_BEING_POLLED.load(Ordering::Relaxed)
}
impl<T, F: Future<Output = T>> Drop for WrappedFuture<T, F> {
fn drop(&mut self) {
ACTIVE_TASKS.fetch_sub(1, Ordering::Relaxed);
}
}
impl<T, F: Future<Output = T>> Future for WrappedFuture<T, F> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
FUTURES_BEING_POLLED.fetch_add(1, Ordering::Relaxed);
POLL_COUNT.fetch_add(1, Ordering::Relaxed);
scopeguard::defer!({
FUTURES_BEING_POLLED.fetch_sub(1, Ordering::Relaxed);
});
let fut = unsafe { self.map_unchecked_mut(|v| &mut v.fut) };
let start = Instant::now();
let res = fut.poll(cx);
log::trace!("poll took {:?}", start.elapsed());
res
}
}
impl<T, F: Future<Output = T> + 'static> WrappedFuture<T, F> {
pub fn new(fut: F) -> Self {
ACTIVE_TASKS.fetch_add(1, Ordering::Relaxed);
WrappedFuture { fut }
}
}