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
#![feature(fnbox)] extern crate spin; extern crate num_cpus; #[macro_use] extern crate lazy_static; use std::sync::Arc; use std::thread::{self, Thread}; use std::boxed::FnBox; use std::mem; use std::error::Error; use std::fmt::{self, Display}; use spin::Mutex as SpinMutex; use threadpool::ThreadPool; mod threadpool; lazy_static! { static ref POOL : SpinMutex<ThreadPool> = SpinMutex::new(ThreadPool::new(num_cpus::get())); } pub type AwaitResult <T> = Result<T, AwaitError>; pub fn promise_future <T> () -> (Promise<T>, Future<T>) where T : Send + 'static { let store = Arc::new(SpinMutex::new((PromiseValue::Impending, None, None))); (Promise(Some(store.clone()), false), Future(FutureInner::Impending(store))) } fn continue_future <T> () -> (Promise<T>, Future<T>) where T : Send + 'static { let store = Arc::new(SpinMutex::new((PromiseValue::Impending, None, None))); (Promise(Some(store.clone()), true), Future(FutureInner::Impending(store))) } pub fn spawn_future <F, T> (func : F) -> Future<T> where F : FnOnce() -> T + Send + 'static, T : Send + 'static { let (p, f) = promise_future(); POOL.lock().execute(move|| p.fulfill(func())); f } #[must_use] pub struct Promise <T> (Option<Arc<SpinMutex<(PromiseValue<T>, Option<Box<FnBox(T) + Send + 'static>>, Option<Thread>)>>>, bool) where T : Send + 'static; impl <T> Promise<T> where T : Send + 'static { pub fn fulfill (mut self, val : T) { let store = self.0.take().unwrap(); let mut lock = store.lock(); if let Some(cont) = lock.1.take() { if self.1 { cont.call_box((val,)); } else { POOL.lock().execute(move|| cont.call_box((val,))); } } else { lock.0 = PromiseValue::Present(val); if let Some(ref thread) = lock.2 { thread.unpark(); } } } } impl <T, E> Promise<Result<T, E>> where T : Send + 'static, E : Send + 'static { #[inline] pub fn ok (self, val : T) { self.fulfill(Ok(val)); } #[inline] pub fn err (self, err : E) { self.fulfill(Err(err)); } } impl <T> Drop for Promise<T> where T : Send + 'static { fn drop (&mut self) { if let Some(store) = self.0.take() { let mut lock = store.lock(); lock.0 = PromiseValue::Broken; if let Some(ref thread) = lock.2 { thread.unpark(); } } } } pub enum PromiseValue <T> where T : Send + 'static { Impending, Present (T), Broken, } impl <T> PromiseValue<T> where T : Send + 'static { pub fn take (&mut self) -> PromiseValue<T> { let mut pv = PromiseValue::Impending; mem::swap(self, &mut pv); pv } } pub struct Future <T> (FutureInner<T>) where T : Send + 'static; enum FutureInner <T> where T : Send + 'static { Impending (Arc<SpinMutex<(PromiseValue<T>, Option<Box<FnBox(T) + Send + 'static>>, Option<Thread>)>>), Present (T), Broken, } impl <T> Future<T> where T : Send + 'static { #[inline] pub fn present (val : T) -> Future<T> { Future(FutureInner::Present(val)) } pub fn poll (&mut self) -> FutureState { let inner = { let store = match self.0 { FutureInner::Impending(ref mut store) => store, FutureInner::Present(..) => return FutureState::Present, FutureInner::Broken => return FutureState::Broken, }; match store.lock().0.take() { PromiseValue::Impending => return FutureState::Impending, PromiseValue::Present(val) => FutureInner::Present(val), PromiseValue::Broken => FutureInner::Broken, } }; self.0 = inner; match self.0 { FutureInner::Impending(..) => FutureState::Impending, FutureInner::Present(..) => FutureState::Present, FutureInner::Broken => FutureState::Broken, } } pub fn await (self) -> AwaitResult<T> { match self.0 { FutureInner::Impending(store) => { loop { { let mut lock = store.lock(); match lock.0.take() { PromiseValue::Impending => (), PromiseValue::Present(val) => return Ok(val), PromiseValue::Broken => return Err(AwaitError::Broken), } if let None = lock.2 { lock.2 = Some(thread::current()); } } thread::park(); } }, FutureInner::Present(val) => Ok(val), FutureInner::Broken => Err(AwaitError::Broken), } } pub fn then <F, U> (self, cont : F) -> Future<U> where F : FnOnce(T) -> U + Send + 'static, U : Send + 'static { match self.0 { FutureInner::Impending(store) => { let mut lock = store.lock(); match lock.0.take() { PromiseValue::Impending => { let (p, f) = continue_future(); lock.1 = Some(Box::new(move|val| p.fulfill(cont(val)))); f }, PromiseValue::Present(val) => { let (p, f) = continue_future(); thread::spawn(move|| p.fulfill(cont(val))); f }, PromiseValue::Broken => Future(FutureInner::Broken), } }, FutureInner::Present(val) => { let (p, f) = continue_future(); thread::spawn(move|| p.fulfill(cont(val))); f }, FutureInner::Broken => Future(FutureInner::Broken), } } } impl <T, E> Future<Result<T, E>> where T : Send + 'static, E : Send + From<AwaitError> + 'static { pub fn result (self) -> Result<T, E> { match self.await() { Ok(res) => res, Err(e) => Err(e.into()), } } pub fn and_then <F, U, G> (self, cont : F) -> Future<Result<U, G>> where F : FnOnce(T) -> Result<U, G> + Send + 'static, U : Send + 'static, G : Send + From<E> + 'static { self.then(|res| match res { Ok(val) => cont(val), Err(e) => Err(e.into()), }) } } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum FutureState { Impending, Present, Broken, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum AwaitError { Broken, } impl Error for AwaitError { fn description (&self) -> &str { match *self { AwaitError::Broken => "Broken future", } } fn cause (&self) -> Option<&Error> { None } } impl Display for AwaitError { fn fmt (&self, fmt : &mut fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> { write!(fmt, "AwaitError: {}", self.description()) } }