fibers/executor/
mod.rs

1// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved.
2// See the LICENSE file at the top-level directory of this distribution.
3
4//! The `Executor` trait and its implementations.
5use futures::{Async, Future};
6use std::io;
7
8pub use self::in_place::{InPlaceExecutor, InPlaceExecutorHandle};
9pub use self::thread_pool::{ThreadPoolExecutor, ThreadPoolExecutorHandle};
10
11use fiber::Spawn;
12use sync::oneshot::{Monitor, MonitorError};
13
14mod in_place;
15mod thread_pool;
16
17/// The `Executor` trait allows for spawning and executing fibers.
18pub trait Executor: Sized {
19    /// The handle type of the executor.
20    type Handle: Spawn + Clone + Send + 'static;
21
22    /// Returns the handle of the executor.
23    fn handle(&self) -> Self::Handle;
24
25    /// Runs one one unit of works.
26    fn run_once(&mut self) -> io::Result<()>;
27
28    /// Runs until the monitored fiber exits.
29    fn run_fiber<T, E>(
30        &mut self,
31        monitor: Monitor<T, E>,
32    ) -> io::Result<Result<T, MonitorError<E>>> {
33        self.run_future(monitor)
34    }
35
36    /// Runs until the future is ready.
37    fn run_future<F: Future>(&mut self, mut future: F) -> io::Result<Result<F::Item, F::Error>> {
38        loop {
39            match future.poll() {
40                Err(e) => return Ok(Err(e)),
41                Ok(Async::Ready(v)) => return Ok(Ok(v)),
42                Ok(Async::NotReady) => {}
43            }
44            self.run_once()?;
45        }
46    }
47
48    /// Runs infinitely until an error happens.
49    fn run(mut self) -> io::Result<()> {
50        loop {
51            self.run_once()?
52        }
53    }
54}