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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Async executor.
//!
//! This crate offers two kinds of executors: single-threaded and multi-threaded.
//!
//! # Examples
//!
//! Run a single-threaded and a multi-threaded executor at the same time:
//!
//! ```
//! use async_channel::unbounded;
//! use async_executor::{Executor, LocalExecutor};
//! use easy_parallel::Parallel;
//!
//! let ex = Executor::new();
//! let local_ex = LocalExecutor::new();
//! let (trigger, shutdown) = unbounded::<()>();
//!
//! Parallel::new()
//!     // Run four executor threads.
//!     .each(0..4, |_| ex.run(shutdown.recv()))
//!     // Run local executor on the current thread.
//!     .finish(|| local_ex.run(async {
//!         println!("Hello world!");
//!         drop(trigger);
//!     }));
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;

use futures_lite::pin;
use scoped_tls::scoped_thread_local;
use waker_fn::waker_fn;

#[cfg(feature = "async-io")]
use async_io::parking;
#[cfg(not(feature = "async-io"))]
use parking;

scoped_thread_local!(static EX: Executor);
scoped_thread_local!(static LOCAL_EX: LocalExecutor);

/// Multi-threaded executor.
///
/// The executor does not spawn threads on its own. Instead, you need to call [`Executor::run()`]
/// on manually spawned executor threads.
///
/// # Examples
///
/// ```
/// use async_channel::unbounded;
/// use async_executor::Executor;
/// use easy_parallel::Parallel;
/// use futures_lite::future;
///
/// let ex = Executor::new();
/// let (signal, shutdown) = unbounded::<()>();
///
/// Parallel::new()
///     // Run four executor threads.
///     .each(0..4, |_| ex.run(shutdown.recv()))
///     // Run the main future on the current thread.
///     .finish(|| future::block_on(async {
///         println!("Hello world!");
///         drop(signal);
///     }));
/// ```
#[derive(Debug)]
pub struct Executor {
    ex: multitask::Executor,
}

impl Executor {
    /// Creates a multi-threaded executor.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::LocalExecutor;
    ///
    /// let local_ex = LocalExecutor::new();
    /// ```
    pub fn new() -> Executor {
        Executor {
            ex: multitask::Executor::new(),
        }
    }

    /// Spawns a task onto the executor.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::Executor;
    ///
    /// let ex = Executor::new();
    ///
    /// let task = ex.spawn(async {
    ///     println!("Hello world");
    /// });
    /// ```
    pub fn spawn<T: Send + 'static>(
        &self,
        future: impl Future<Output = T> + Send + 'static,
    ) -> Task<T> {
        Task(self.ex.spawn(future))
    }

    /// Enters the context of an executor.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::{Executor, Task};
    ///
    /// let ex = Executor::new();
    ///
    /// ex.enter(|| {
    ///     // `Task::spawn()` now knows which executor to spawn onto.
    ///     let task = Task::spawn(async {
    ///         println!("Hello world");
    ///     });
    /// });
    /// ```
    pub fn enter<T>(&self, f: impl FnOnce() -> T) -> T {
        if EX.is_set() {
            panic!("cannot call `Executor::enter()` if already inside an `Executor`");
        }
        EX.set(self, f)
    }

    /// Runs the executor until the given future completes.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::Executor;
    ///
    /// let ex = Executor::new();
    ///
    /// let task = ex.spawn(async { 1 + 2 });
    /// let res = ex.run(async { task.await * 2 });
    ///
    /// assert_eq!(res, 6);
    /// ```
    pub fn run<T>(&self, future: impl Future<Output = T>) -> T {
        self.enter(|| {
            let (p, u) = parking::pair();

            let ticker = self.ex.ticker({
                let u = u.clone();
                move || u.unpark()
            });

            pin!(future);
            let waker = waker_fn(move || u.unpark());
            let cx = &mut Context::from_waker(&waker);

            'start: loop {
                if let Poll::Ready(t) = future.as_mut().poll(cx) {
                    break t;
                }

                for _ in 0..200 {
                    if !ticker.tick() {
                        p.park();
                        continue 'start;
                    }
                }
                p.park_timeout(Duration::from_secs(0));
            }
        })
    }
}

impl Default for Executor {
    fn default() -> Executor {
        Executor::new()
    }
}

/// Single-threaded executor.
///
/// The executor can only be run on the thread that created it.
///
/// # Examples
///
/// ```
/// use async_executor::LocalExecutor;
///
/// let local_ex = LocalExecutor::new();
///
/// local_ex.run(async {
///     println!("Hello world!");
/// });
/// ```
#[derive(Debug)]
pub struct LocalExecutor {
    ex: multitask::LocalExecutor,
    parker: parking::Parker,
}

impl LocalExecutor {
    /// Creates a single-threaded executor.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::LocalExecutor;
    ///
    /// let local_ex = LocalExecutor::new();
    /// ```
    pub fn new() -> LocalExecutor {
        let (p, u) = parking::pair();
        LocalExecutor {
            ex: multitask::LocalExecutor::new(move || u.unpark()),
            parker: p,
        }
    }

    /// Spawns a task onto the executor.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::LocalExecutor;
    ///
    /// let local_ex = LocalExecutor::new();
    ///
    /// let task = local_ex.spawn(async {
    ///     println!("Hello world");
    /// });
    /// ```
    pub fn spawn<T: 'static>(&self, future: impl Future<Output = T> + 'static) -> Task<T> {
        Task(self.ex.spawn(future))
    }

    /// Runs the executor until the given future completes.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::LocalExecutor;
    ///
    /// let local_ex = LocalExecutor::new();
    ///
    /// let task = local_ex.spawn(async { 1 + 2 });
    /// let res = local_ex.run(async { task.await * 2 });
    ///
    /// assert_eq!(res, 6);
    /// ```
    pub fn run<T>(&self, future: impl Future<Output = T>) -> T {
        pin!(future);

        let u = self.parker.unparker();
        let waker = waker_fn(move || u.unpark());
        let cx = &mut Context::from_waker(&waker);

        LOCAL_EX.set(self, || {
            'start: loop {
                if let Poll::Ready(t) = future.as_mut().poll(cx) {
                    break t;
                }

                for _ in 0..200 {
                    if !self.ex.tick() {
                        self.parker.park();
                        continue 'start;
                    }
                }
                self.parker.park_timeout(Duration::from_secs(0));
            }
        })
    }
}

impl Default for LocalExecutor {
    fn default() -> LocalExecutor {
        LocalExecutor::new()
    }
}

/// A spawned future.
///
/// Tasks are also futures themselves and yield the output of the spawned future.
///
/// When a task is dropped, its gets canceled and won't be polled again. To cancel a task a bit
/// more gracefully and wait until it stops running, use the [`cancel()`][`Task::cancel()`] method.
///
/// Tasks that panic get immediately canceled. Awaiting a canceled task also causes a panic.
///
/// # Examples
///
/// ```
/// use async_executor::{Executor, Task};
///
/// let ex = Executor::new();
///
/// ex.run(async {
///     let task = Task::spawn(async {
///         println!("Hello from a task!");
///         1 + 2
///     });
///
///     assert_eq!(task.await, 3);
/// });
/// ```
#[must_use = "tasks get canceled when dropped, use `.detach()` to run them in the background"]
#[derive(Debug)]
pub struct Task<T>(multitask::Task<T>);

impl<T> Task<T> {
    /// Spawns a task onto the current multi-threaded or single-threaded executor.
    ///
    /// If called from an [`Executor`] (preferred) or from a [`LocalExecutor`], the task is spawned
    /// on it.
    ///
    /// Otherwise, this method panics.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::{Executor, Task};
    ///
    /// let ex = Executor::new();
    ///
    /// ex.run(async {
    ///     let task = Task::spawn(async { 1 + 2 });
    ///     assert_eq!(task.await, 3);
    /// });
    /// ```
    ///
    /// ```
    /// use async_executor::{LocalExecutor, Task};
    ///
    /// let local_ex = LocalExecutor::new();
    ///
    /// local_ex.run(async {
    ///     let task = Task::spawn(async { 1 + 2 });
    ///     assert_eq!(task.await, 3);
    /// });
    /// ```
    pub fn spawn(future: impl Future<Output = T> + Send + 'static) -> Task<T>
    where
        T: Send + 'static,
    {
        if EX.is_set() {
            EX.with(|ex| ex.spawn(future))
        } else if LOCAL_EX.is_set() {
            LOCAL_EX.with(|local_ex| local_ex.spawn(future))
        } else {
            panic!("`Task::spawn()` must be called from an `Executor` or `LocalExecutor`")
        }
    }

    /// Spawns a task onto the current single-threaded executor.
    ///
    /// If called from a [`LocalExecutor`], the task is spawned on it.
    ///
    /// Otherwise, this method panics.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::{LocalExecutor, Task};
    ///
    /// let local_ex = LocalExecutor::new();
    ///
    /// local_ex.run(async {
    ///     let task = Task::local(async { 1 + 2 });
    ///     assert_eq!(task.await, 3);
    /// });
    /// ```
    pub fn local(future: impl Future<Output = T> + 'static) -> Task<T>
    where
        T: 'static,
    {
        if LOCAL_EX.is_set() {
            LOCAL_EX.with(|local_ex| local_ex.spawn(future))
        } else {
            panic!("`Task::local()` must be called from a `LocalExecutor`")
        }
    }

    /// Detaches the task to let it keep running in the background.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::{Executor, Task};
    /// use futures_lite::future;
    ///
    /// let ex = Executor::new();
    ///
    /// ex.spawn(async {
    ///     loop {
    ///         println!("I'm a background task looping forever.");
    ///         future::yield_now().await;
    ///     }
    /// })
    /// .detach();
    ///
    /// ex.run(future::yield_now());
    /// ```
    pub fn detach(self) {
        self.0.detach();
    }

    /// Cancels the task and waits for it to stop running.
    ///
    /// Returns the task's output if it was completed just before it got canceled, or [`None`] if
    /// it didn't complete.
    ///
    /// While it's possible to simply drop the [`Task`] to cancel it, this is a cleaner way of
    /// canceling because it also waits for the task to stop running.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_executor::{Executor, Task};
    /// use futures_lite::future;
    ///
    /// let ex = Executor::new();
    ///
    /// let task = ex.spawn(async {
    ///     loop {
    ///         println!("Even though I'm in an infinite loop, you can still cancel me!");
    ///         future::yield_now().await;
    ///     }
    /// });
    ///
    /// ex.run(async {
    ///     task.cancel().await;
    /// });
    /// ```
    pub async fn cancel(self) -> Option<T> {
        self.0.cancel().await
    }
}

impl<T> Future for Task<T> {
    type Output = T;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.0).poll(cx)
    }
}