1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-06-29 01:50:35 +02:00

restore 0.1 behavior

This commit is contained in:
Nikolay Kim
2019-12-02 22:47:49 +06:00
parent 9f575418c1
commit c0ede65317
3 changed files with 32 additions and 14 deletions

View File

@ -1,15 +1,15 @@
//! Thread pool for blocking operations
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use derive_more::Display;
use futures::channel::oneshot;
use parking_lot::Mutex;
use threadpool::ThreadPool;
pub use futures::channel::oneshot::Canceled;
/// Env variable for default cpu pool size.
const ENV_CPU_POOL_VAR: &str = "ACTIX_THREADPOOL";
@ -39,12 +39,22 @@ thread_local! {
};
}
/// Blocking operation execution error
#[derive(Debug, Display)]
pub enum BlockingError<E: fmt::Debug> {
#[display(fmt = "{:?}", _0)]
Error(E),
#[display(fmt = "Thread pool is gone")]
Canceled,
}
/// Execute blocking function on a thread pool, returns future that resolves
/// to result of the function execution.
pub fn run<F, I>(f: F) -> CpuFuture<I>
pub fn run<F, I, E>(f: F) -> CpuFuture<I, E>
where
F: FnOnce() -> I + Send + 'static,
F: FnOnce() -> Result<I, E> + Send + 'static,
I: Send + 'static,
E: Send + fmt::Debug + 'static,
{
let (tx, rx) = oneshot::channel();
POOL.with(|pool| {
@ -60,16 +70,18 @@ where
/// Blocking operation completion future. It resolves with results
/// of blocking function execution.
pub struct CpuFuture<I> {
rx: oneshot::Receiver<I>,
pub struct CpuFuture<I, E> {
rx: oneshot::Receiver<Result<I, E>>,
}
impl<I> Future for CpuFuture<I> {
type Output = Result<I, Canceled>;
impl<I, E: fmt::Debug> Future for CpuFuture<I, E> {
type Output = Result<I, BlockingError<E>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let rx = Pin::new(&mut Pin::get_mut(self).rx);
let res = futures::ready!(rx.poll(cx));
Poll::Ready(res.map_err(|_| Canceled))
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let rx = Pin::new(&mut self.rx);
let res = futures::ready!(rx.poll(cx))
.map_err(|_| BlockingError::Canceled)
.and_then(|res| res.map_err(BlockingError::Error));
Poll::Ready(res)
}
}