#![deny(missing_docs)]
extern crate crossbeam;
#[macro_use]
extern crate futures;
extern crate num_cpus;
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use crossbeam::sync::MsQueue;
use futures::{IntoFuture, Future, oneshot, Oneshot, Complete, Poll, Async};
use futures::task::{self, Run, Executor};
pub struct CpuPool {
inner: Arc<Inner>,
}
struct Sender<F, T> {
fut: F,
tx: Option<Complete<T>>,
}
fn _assert() {
fn _assert_send<T: Send>() {}
fn _assert_sync<T: Sync>() {}
_assert_send::<CpuPool>();
_assert_sync::<CpuPool>();
}
struct Inner {
queue: MsQueue<Message>,
cnt: AtomicUsize,
size: usize,
}
pub struct CpuFuture<T, E> {
inner: Oneshot<thread::Result<Result<T, E>>>,
}
enum Message {
Run(Run),
Close,
}
impl CpuPool {
pub fn new(size: usize) -> CpuPool {
let pool = CpuPool {
inner: Arc::new(Inner {
queue: MsQueue::new(),
cnt: AtomicUsize::new(1),
size: size,
}),
};
for _ in 0..size {
let inner = pool.inner.clone();
thread::spawn(move || work(&inner));
}
return pool
}
pub fn new_num_cpus() -> CpuPool {
CpuPool::new(num_cpus::get())
}
pub fn spawn<F>(&self, f: F) -> CpuFuture<F::Item, F::Error>
where F: Future + Send + 'static,
F::Item: Send + 'static,
F::Error: Send + 'static,
{
let (tx, rx) = oneshot();
let sender = Sender {
fut: AssertUnwindSafe(f).catch_unwind(),
tx: Some(tx),
};
task::spawn(sender).execute(self.inner.clone());
CpuFuture { inner: rx }
}
pub fn spawn_fn<F, R>(&self, f: F) -> CpuFuture<R::Item, R::Error>
where F: FnOnce() -> R + Send + 'static,
R: IntoFuture + 'static,
R::Future: Send + 'static,
R::Item: Send + 'static,
R::Error: Send + 'static,
{
self.spawn(futures::lazy(f))
}
}
fn work(inner: &Inner) {
loop {
match inner.queue.pop() {
Message::Run(r) => r.run(),
Message::Close => break,
}
}
}
impl Clone for CpuPool {
fn clone(&self) -> CpuPool {
self.inner.cnt.fetch_add(1, Ordering::Relaxed);
CpuPool { inner: self.inner.clone() }
}
}
impl Drop for CpuPool {
fn drop(&mut self) {
if self.inner.cnt.fetch_sub(1, Ordering::Relaxed) == 1 {
for _ in 0..self.inner.size {
self.inner.queue.push(Message::Close);
}
}
}
}
impl Executor for Inner {
fn execute(&self, run: Run) {
self.queue.push(Message::Run(run))
}
}
impl<T: Send + 'static, E: Send + 'static> Future for CpuFuture<T, E> {
type Item = T;
type Error = E;
fn poll(&mut self) -> Poll<T, E> {
match self.inner.poll().expect("shouldn't be canceled") {
Async::Ready(Ok(Ok(e))) => Ok(e.into()),
Async::Ready(Ok(Err(e))) => Err(e),
Async::Ready(Err(e)) => panic::resume_unwind(e),
Async::NotReady => Ok(Async::NotReady),
}
}
}
impl<F: Future> Future for Sender<F, Result<F::Item, F::Error>> {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
if let Ok(Async::Ready(_)) = self.tx.as_mut().unwrap().poll_cancel() {
return Ok(().into())
}
let res = match self.fut.poll() {
Ok(Async::Ready(e)) => Ok(e),
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(e) => Err(e),
};
self.tx.take().unwrap().complete(res);
Ok(Async::Ready(()))
}
}