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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use std::cell::Cell;
use std::future::Future;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::thread;
use std::time::{Duration, Instant};
use futures_lite::pin;
use once_cell::sync::Lazy;
use waker_fn::waker_fn;
use crate::reactor::Reactor;
static BLOCK_ON_COUNT: AtomicUsize = AtomicUsize::new(0);
static UNPARKER: Lazy<parking::Unparker> = Lazy::new(|| {
let (parker, unparker) = parking::pair();
thread::Builder::new()
.name("async-io".to_string())
.spawn(move || main_loop(parker))
.expect("cannot spawn async-io thread");
unparker
});
pub(crate) fn init() {
Lazy::force(&UNPARKER);
}
fn main_loop(parker: parking::Parker) {
let mut last_tick = 0;
let mut sleeps = 0u64;
loop {
let tick = Reactor::get().ticker();
if last_tick == tick {
let reactor_lock = if sleeps >= 10 {
Some(Reactor::get().lock())
} else {
Reactor::get().try_lock()
};
if let Some(mut reactor_lock) = reactor_lock {
log::trace!("main_loop: waiting on I/O");
reactor_lock.react(None).ok();
last_tick = Reactor::get().ticker();
sleeps = 0;
}
} else {
last_tick = tick;
}
if BLOCK_ON_COUNT.load(Ordering::SeqCst) > 0 {
let delay_us = [50, 75, 100, 250, 500, 750, 1000, 2500, 5000]
.get(sleeps as usize)
.unwrap_or(&10_000);
log::trace!("main_loop: sleeping for {} us", delay_us);
if parker.park_timeout(Duration::from_micros(*delay_us)) {
log::trace!("main_loop: notified");
last_tick = Reactor::get().ticker();
sleeps = 0;
} else {
sleeps += 1;
}
}
}
}
pub fn block_on<T>(future: impl Future<Output = T>) -> T {
log::trace!("block_on()");
BLOCK_ON_COUNT.fetch_add(1, Ordering::SeqCst);
let _guard = CallOnDrop(|| {
BLOCK_ON_COUNT.fetch_sub(1, Ordering::SeqCst);
UNPARKER.unpark();
});
let (p, u) = parking::pair();
let io_blocked = Arc::new(AtomicBool::new(false));
thread_local! {
static IO_POLLING: Cell<bool> = Cell::new(false);
}
let waker = waker_fn({
let io_blocked = io_blocked.clone();
move || {
if u.unpark() {
if !IO_POLLING.with(Cell::get) && io_blocked.load(Ordering::SeqCst) {
Reactor::get().notify();
}
}
}
});
let cx = &mut Context::from_waker(&waker);
pin!(future);
loop {
if let Poll::Ready(t) = future.as_mut().poll(cx) {
log::trace!("block_on: completed");
return t;
}
if p.park_timeout(Duration::from_secs(0)) {
log::trace!("block_on: notified");
if let Some(mut reactor_lock) = Reactor::get().try_lock() {
IO_POLLING.with(|io| io.set(true));
let _guard = CallOnDrop(|| {
IO_POLLING.with(|io| io.set(false));
});
reactor_lock.react(Some(Duration::from_secs(0))).ok();
}
continue;
}
if let Some(mut reactor_lock) = Reactor::get().try_lock() {
let start = Instant::now();
loop {
IO_POLLING.with(|io| io.set(true));
io_blocked.store(true, Ordering::SeqCst);
let _guard = CallOnDrop(|| {
IO_POLLING.with(|io| io.set(false));
io_blocked.store(false, Ordering::SeqCst);
});
if p.park_timeout(Duration::from_secs(0)) {
log::trace!("block_on: notified");
break;
}
log::trace!("block_on: waiting on I/O");
reactor_lock.react(None).ok();
if p.park_timeout(Duration::from_secs(0)) {
log::trace!("block_on: notified");
break;
}
if start.elapsed() > Duration::from_micros(500) {
log::trace!("block_on: stops hogging the reactor");
drop(reactor_lock);
UNPARKER.unpark();
p.park();
break;
}
}
} else {
log::trace!("block_on: sleep until notification");
p.park();
}
}
}
struct CallOnDrop<F: Fn()>(F);
impl<F: Fn()> Drop for CallOnDrop<F> {
fn drop(&mut self) {
(self.0)();
}
}