#![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>,
}
pub struct Builder {
pool_size: usize,
after_start: Option<Arc<Fn() + Send + Sync>>,
before_stop: Option<Arc<Fn() + Send + Sync>>,
}
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,
after_start: Option<Arc<Fn() + Send + Sync>>,
before_stop: Option<Arc<Fn() + Send + Sync>>,
}
#[must_use]
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 {
Builder::new().pool_size(size).create()
}
pub fn new_num_cpus() -> CpuPool {
Builder::new().create()
}
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) {
inner.after_start.as_ref().map(|fun| fun());
loop {
match inner.queue.pop() {
Message::Run(r) => r.run(),
Message::Close => break,
}
}
inner.before_stop.as_ref().map(|fun| fun());
}
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(()))
}
}
impl Builder {
pub fn new() -> Builder {
Builder {
pool_size: num_cpus::get(),
after_start: None,
before_stop: None,
}
}
pub fn pool_size(&mut self, size: usize) -> &mut Self {
self.pool_size = size;
self
}
pub fn after_start<F>(&mut self, f: F) -> &mut Self
where F: Fn() + Send + Sync + 'static
{
self.after_start = Some(Arc::new(f));
self
}
pub fn before_stop<F>(&mut self, f: F) -> &mut Self
where F: Fn() + Send + Sync + 'static
{
self.before_stop = Some(Arc::new(f));
self
}
pub fn create(&mut self) -> CpuPool {
let pool = CpuPool {
inner: Arc::new(Inner {
queue: MsQueue::new(),
cnt: AtomicUsize::new(1),
size: self.pool_size,
after_start: self.after_start.clone(),
before_stop: self.before_stop.clone(),
}),
};
assert!(self.pool_size > 0);
for _ in 0..self.pool_size {
let inner = pool.inner.clone();
thread::spawn(move || work(&inner));
}
return pool
}
}