futures_executor/local_pool.rs
1use crate::enter;
2use futures_core::future::Future;
3use futures_core::stream::Stream;
4use futures_core::task::{Context, Poll};
5use futures_task::{waker_ref, ArcWake};
6use futures_task::{FutureObj, LocalFutureObj, LocalSpawn, Spawn, SpawnError};
7use futures_util::stream::FuturesUnordered;
8use futures_util::stream::StreamExt;
9use std::cell::RefCell;
10use std::ops::{Deref, DerefMut};
11use std::pin::pin;
12use std::rc::{Rc, Weak};
13use std::sync::{
14 atomic::{AtomicBool, Ordering},
15 Arc,
16};
17use std::thread::{self, Thread};
18use std::vec::Vec;
19
20/// A single-threaded task pool for polling futures to completion.
21///
22/// This executor allows you to multiplex any number of tasks onto a single
23/// thread. It's appropriate to poll strictly I/O-bound futures that do very
24/// little work in between I/O actions.
25///
26/// To get a handle to the pool that implements [`Spawn`], use the
27/// [`spawner()`](LocalPool::spawner) method. Because the executor is
28/// single-threaded, it supports a special form of task spawning for non-`Send`
29/// futures, via [`spawn_local_obj`](futures_task::LocalSpawn::spawn_local_obj).
30#[derive(Debug)]
31pub struct LocalPool {
32 pool: FuturesUnordered<LocalFutureObj<'static, ()>>,
33 incoming: Rc<Incoming>,
34}
35
36/// A handle to a [`LocalPool`] that implements [`Spawn`].
37#[derive(Clone, Debug)]
38pub struct LocalSpawner {
39 incoming: Weak<Incoming>,
40}
41
42type Incoming = RefCell<Vec<LocalFutureObj<'static, ()>>>;
43
44pub(crate) struct ThreadNotify {
45 /// The (single) executor thread.
46 thread: Thread,
47 /// A flag to ensure a wakeup (i.e. `unpark()`) is not "forgotten"
48 /// before the next `park()`, which may otherwise happen if the code
49 /// being executed as part of the future(s) being polled makes use of
50 /// park / unpark calls of its own, i.e. we cannot assume that no other
51 /// code uses park / unpark on the executing `thread`.
52 unparked: AtomicBool,
53}
54
55std::thread_local! {
56 static CURRENT_THREAD_NOTIFY: Arc<ThreadNotify> = Arc::new(ThreadNotify {
57 thread: thread::current(),
58 unparked: AtomicBool::new(false),
59 });
60}
61
62impl ArcWake for ThreadNotify {
63 fn wake_by_ref(arc_self: &Arc<Self>) {
64 // Make sure the wakeup is remembered until the next `park()`.
65 let unparked = arc_self.unparked.swap(true, Ordering::Release);
66 if !unparked {
67 // If the thread has not been unparked yet, it must be done
68 // now. If it was actually parked, it will run again,
69 // otherwise the token made available by `unpark`
70 // may be consumed before reaching `park()`, but `unparked`
71 // ensures it is not forgotten.
72 arc_self.thread.unpark();
73 }
74 }
75}
76
77// Set up and run a basic single-threaded spawner loop, invoking `f` on each
78// turn.
79fn run_executor<T, F: FnMut(&mut Context<'_>) -> Poll<T>>(mut f: F) -> T {
80 let _enter = enter().expect(
81 "cannot execute `LocalPool` executor from within \
82 another executor",
83 );
84
85 CURRENT_THREAD_NOTIFY.with(|thread_notify| {
86 let waker = waker_ref(thread_notify);
87 let mut cx = Context::from_waker(&waker);
88 loop {
89 if let Poll::Ready(t) = f(&mut cx) {
90 return t;
91 }
92
93 // Wait for a wakeup.
94 while !thread_notify.unparked.swap(false, Ordering::Acquire) {
95 // No wakeup occurred. It may occur now, right before parking,
96 // but in that case the token made available by `unpark()`
97 // is guaranteed to still be available and `park()` is a no-op.
98 thread::park();
99 }
100 }
101 })
102}
103
104/// Check for a wakeup, but don't consume it.
105fn woken() -> bool {
106 CURRENT_THREAD_NOTIFY.with(|thread_notify| thread_notify.unparked.load(Ordering::Acquire))
107}
108
109impl LocalPool {
110 /// Create a new, empty pool of tasks.
111 pub fn new() -> Self {
112 Self { pool: FuturesUnordered::new(), incoming: Default::default() }
113 }
114
115 /// Get a clonable handle to the pool as a [`Spawn`].
116 pub fn spawner(&self) -> LocalSpawner {
117 LocalSpawner { incoming: Rc::downgrade(&self.incoming) }
118 }
119
120 /// Run all tasks in the pool to completion.
121 ///
122 /// ```
123 /// use futures::executor::LocalPool;
124 ///
125 /// let mut pool = LocalPool::new();
126 ///
127 /// // ... spawn some initial tasks using `spawn.spawn()` or `spawn.spawn_local()`
128 ///
129 /// // run *all* tasks in the pool to completion, including any newly-spawned ones.
130 /// pool.run();
131 /// ```
132 ///
133 /// The function will block the calling thread until *all* tasks in the pool
134 /// are complete, including any spawned while running existing tasks.
135 pub fn run(&mut self) {
136 run_executor(|cx| self.poll_pool(cx))
137 }
138
139 /// Runs all the tasks in the pool until the given future completes.
140 ///
141 /// ```
142 /// use futures::executor::LocalPool;
143 ///
144 /// let mut pool = LocalPool::new();
145 /// # let my_app = async {};
146 ///
147 /// // run tasks in the pool until `my_app` completes
148 /// pool.run_until(my_app);
149 /// ```
150 ///
151 /// The function will block the calling thread *only* until the future `f`
152 /// completes; there may still be incomplete tasks in the pool, which will
153 /// be inert after the call completes, but can continue with further use of
154 /// one of the pool's run or poll methods. While the function is running,
155 /// however, all tasks in the pool will try to make progress.
156 pub fn run_until<F: Future>(&mut self, future: F) -> F::Output {
157 let mut future = pin!(future);
158
159 run_executor(|cx| {
160 {
161 // if our main task is done, so are we
162 let result = future.as_mut().poll(cx);
163 if let Poll::Ready(output) = result {
164 return Poll::Ready(output);
165 }
166 }
167
168 let _ = self.poll_pool(cx);
169 Poll::Pending
170 })
171 }
172
173 /// Runs all tasks and returns after completing one future or until no more progress
174 /// can be made. Returns `true` if one future was completed, `false` otherwise.
175 ///
176 /// ```
177 /// use futures::executor::LocalPool;
178 /// use futures::task::LocalSpawnExt;
179 /// use futures::future::{ready, pending};
180 ///
181 /// let mut pool = LocalPool::new();
182 /// let spawner = pool.spawner();
183 ///
184 /// spawner.spawn_local(ready(())).unwrap();
185 /// spawner.spawn_local(ready(())).unwrap();
186 /// spawner.spawn_local(pending()).unwrap();
187 ///
188 /// // Run the two ready tasks and return true for them.
189 /// pool.try_run_one(); // returns true after completing one of the ready futures
190 /// pool.try_run_one(); // returns true after completing the other ready future
191 ///
192 /// // the remaining task can not be completed
193 /// assert!(!pool.try_run_one()); // returns false
194 /// ```
195 ///
196 /// This function will not block the calling thread and will return the moment
197 /// that there are no tasks left for which progress can be made or after exactly one
198 /// task was completed; Remaining incomplete tasks in the pool can continue with
199 /// further use of one of the pool's run or poll methods.
200 /// Though only one task will be completed, progress may be made on multiple tasks.
201 pub fn try_run_one(&mut self) -> bool {
202 run_executor(|cx| {
203 loop {
204 self.drain_incoming();
205
206 match self.pool.poll_next_unpin(cx) {
207 // Success!
208 Poll::Ready(Some(())) => return Poll::Ready(true),
209 // The pool was empty.
210 Poll::Ready(None) => return Poll::Ready(false),
211 Poll::Pending => (),
212 }
213
214 if !self.incoming.borrow().is_empty() {
215 // New tasks were spawned; try again.
216 continue;
217 } else if woken() {
218 // The pool yielded to us, but there's more progress to be made.
219 return Poll::Pending;
220 } else {
221 return Poll::Ready(false);
222 }
223 }
224 })
225 }
226
227 /// Runs all tasks in the pool and returns if no more progress can be made
228 /// on any task.
229 ///
230 /// ```
231 /// use futures::executor::LocalPool;
232 /// use futures::task::LocalSpawnExt;
233 /// use futures::future::{ready, pending};
234 ///
235 /// let mut pool = LocalPool::new();
236 /// let spawner = pool.spawner();
237 ///
238 /// spawner.spawn_local(ready(())).unwrap();
239 /// spawner.spawn_local(ready(())).unwrap();
240 /// spawner.spawn_local(pending()).unwrap();
241 ///
242 /// // Runs the two ready task and returns.
243 /// // The empty task remains in the pool.
244 /// pool.run_until_stalled();
245 /// ```
246 ///
247 /// This function will not block the calling thread and will return the moment
248 /// that there are no tasks left for which progress can be made;
249 /// remaining incomplete tasks in the pool can continue with further use of one
250 /// of the pool's run or poll methods. While the function is running, all tasks
251 /// in the pool will try to make progress.
252 pub fn run_until_stalled(&mut self) {
253 run_executor(|cx| match self.poll_pool(cx) {
254 // The pool is empty.
255 Poll::Ready(()) => Poll::Ready(()),
256 Poll::Pending => {
257 if woken() {
258 Poll::Pending
259 } else {
260 // We're stalled for now.
261 Poll::Ready(())
262 }
263 }
264 });
265 }
266
267 /// Poll `self.pool`, re-filling it with any newly-spawned tasks.
268 /// Repeat until either the pool is empty, or it returns `Pending`.
269 ///
270 /// Returns `Ready` if the pool was empty, and `Pending` otherwise.
271 ///
272 /// NOTE: the pool may call `wake`, so `Pending` doesn't necessarily
273 /// mean that the pool can't make progress.
274 fn poll_pool(&mut self, cx: &mut Context<'_>) -> Poll<()> {
275 loop {
276 self.drain_incoming();
277
278 let pool_ret = self.pool.poll_next_unpin(cx);
279
280 // We queued up some new tasks; add them and poll again.
281 if !self.incoming.borrow().is_empty() {
282 continue;
283 }
284
285 match pool_ret {
286 Poll::Ready(Some(())) => continue,
287 Poll::Ready(None) => return Poll::Ready(()),
288 Poll::Pending => return Poll::Pending,
289 }
290 }
291 }
292
293 /// Empty the incoming queue of newly-spawned tasks.
294 fn drain_incoming(&mut self) {
295 let mut incoming = self.incoming.borrow_mut();
296 for task in incoming.drain(..) {
297 self.pool.push(task)
298 }
299 }
300}
301
302impl Default for LocalPool {
303 fn default() -> Self {
304 Self::new()
305 }
306}
307
308/// Run a future to completion on the current thread.
309///
310/// This function will block the caller until the given future has completed.
311///
312/// Use a [`LocalPool`] if you need finer-grained control over spawned tasks.
313pub fn block_on<F: Future>(f: F) -> F::Output {
314 let mut f = pin!(f);
315 run_executor(|cx| f.as_mut().poll(cx))
316}
317
318/// Turn a stream into a blocking iterator.
319///
320/// When `next` is called on the resulting `BlockingStream`, the caller
321/// will be blocked until the next element of the `Stream` becomes available.
322pub fn block_on_stream<S: Stream + Unpin>(stream: S) -> BlockingStream<S> {
323 BlockingStream { stream }
324}
325
326/// An iterator which blocks on values from a stream until they become available.
327#[derive(Debug)]
328pub struct BlockingStream<S: Stream + Unpin> {
329 stream: S,
330}
331
332impl<S: Stream + Unpin> Deref for BlockingStream<S> {
333 type Target = S;
334 fn deref(&self) -> &Self::Target {
335 &self.stream
336 }
337}
338
339impl<S: Stream + Unpin> DerefMut for BlockingStream<S> {
340 fn deref_mut(&mut self) -> &mut Self::Target {
341 &mut self.stream
342 }
343}
344
345impl<S: Stream + Unpin> BlockingStream<S> {
346 /// Convert this `BlockingStream` into the inner `Stream` type.
347 pub fn into_inner(self) -> S {
348 self.stream
349 }
350}
351
352impl<S: Stream + Unpin> Iterator for BlockingStream<S> {
353 type Item = S::Item;
354
355 fn next(&mut self) -> Option<Self::Item> {
356 LocalPool::new().run_until(self.stream.next())
357 }
358
359 fn size_hint(&self) -> (usize, Option<usize>) {
360 self.stream.size_hint()
361 }
362}
363
364impl Spawn for LocalSpawner {
365 fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> {
366 if let Some(incoming) = self.incoming.upgrade() {
367 incoming.borrow_mut().push(future.into());
368 Ok(())
369 } else {
370 Err(SpawnError::shutdown())
371 }
372 }
373
374 fn status(&self) -> Result<(), SpawnError> {
375 if self.incoming.upgrade().is_some() {
376 Ok(())
377 } else {
378 Err(SpawnError::shutdown())
379 }
380 }
381}
382
383impl LocalSpawn for LocalSpawner {
384 fn spawn_local_obj(&self, future: LocalFutureObj<'static, ()>) -> Result<(), SpawnError> {
385 if let Some(incoming) = self.incoming.upgrade() {
386 incoming.borrow_mut().push(future);
387 Ok(())
388 } else {
389 Err(SpawnError::shutdown())
390 }
391 }
392
393 fn status_local(&self) -> Result<(), SpawnError> {
394 if self.incoming.upgrade().is_some() {
395 Ok(())
396 } else {
397 Err(SpawnError::shutdown())
398 }
399 }
400}