| 1 | //! Implementation of a task, as well as underlying primitives used to drive |
| 2 | //! their execution. |
| 3 | |
| 4 | use std::{ |
| 5 | any::Any, |
| 6 | fmt, |
| 7 | future::Future, |
| 8 | panic::{catch_unwind, resume_unwind, AssertUnwindSafe}, |
| 9 | pin::Pin, |
| 10 | sync::{Arc, Mutex}, |
| 11 | task::{Context, Poll, Waker}, |
| 12 | thread, |
| 13 | time::{Duration, Instant}, |
| 14 | }; |
| 15 | |
| 16 | /// A type of future representing the result of a background computation in a |
| 17 | /// thread pool. Tasks are returned when submitting a closure or future to a |
| 18 | /// thread pool. |
| 19 | /// |
| 20 | /// Tasks implement [`Future`], so you can `.await` their completion |
| 21 | /// asynchronously. Or, you can wait for their completion synchronously using |
| 22 | /// the various [`join`](Task::join) methods provided. |
| 23 | /// |
| 24 | /// Dropping a task detaches the running task, but does not cancel it. The task |
| 25 | /// will continue to run on the thread pool until completion, but there will no |
| 26 | /// longer be any way to check its completion or to retrieve its returned value. |
| 27 | /// |
| 28 | /// # Examples |
| 29 | /// |
| 30 | /// Creating a task: |
| 31 | /// |
| 32 | /// ``` |
| 33 | /// use threadfin::ThreadPool; |
| 34 | /// |
| 35 | /// let pool = ThreadPool::new(); |
| 36 | /// |
| 37 | /// let task = pool.execute(|| { |
| 38 | /// // do some work |
| 39 | /// }); |
| 40 | /// ``` |
| 41 | /// |
| 42 | /// Blocking on a task: |
| 43 | /// |
| 44 | /// ``` |
| 45 | /// use threadfin::ThreadPool; |
| 46 | /// |
| 47 | /// let pool = ThreadPool::new(); |
| 48 | /// |
| 49 | /// let task = pool.execute(|| { |
| 50 | /// // some expensive computation |
| 51 | /// 2 + 2 |
| 52 | /// }); |
| 53 | /// |
| 54 | /// // do something in the meantime |
| 55 | /// |
| 56 | /// // now block on the result |
| 57 | /// let sum = task.join(); |
| 58 | /// assert_eq!(sum, 4); |
| 59 | /// ``` |
| 60 | /// |
| 61 | /// Awaiting a task asynchronously: |
| 62 | /// |
| 63 | /// ``` |
| 64 | /// # threadfin::common().execute_future(async { |
| 65 | /// use threadfin::ThreadPool; |
| 66 | /// |
| 67 | /// let pool = ThreadPool::new(); |
| 68 | /// |
| 69 | /// let task = pool.execute(|| { |
| 70 | /// // some expensive, synchronous computation |
| 71 | /// 2 + 2 |
| 72 | /// }); |
| 73 | /// |
| 74 | /// // do something in the meantime |
| 75 | /// |
| 76 | /// // now await on the result |
| 77 | /// let sum = task.await; |
| 78 | /// assert_eq!(sum, 4); |
| 79 | /// # }).join(); |
| 80 | /// ``` |
| 81 | /// |
| 82 | /// Detaching a task: |
| 83 | /// |
| 84 | /// ``` |
| 85 | /// use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; |
| 86 | /// use std::thread::sleep; |
| 87 | /// use std::time::Duration; |
| 88 | /// use threadfin::ThreadPool; |
| 89 | /// |
| 90 | /// let pool = Arc::new(ThreadPool::new()); |
| 91 | /// let completed = Arc::new(AtomicBool::from(false)); |
| 92 | /// |
| 93 | /// // Clone the shared values to be used inside the task. |
| 94 | /// let pool_clone = pool.clone(); |
| 95 | /// let completed_clone = completed.clone(); |
| 96 | /// |
| 97 | /// pool.execute(move || { |
| 98 | /// let _inner_task = pool_clone.execute(move || { |
| 99 | /// // Short delay simulating some work. |
| 100 | /// sleep(Duration::from_millis(100)); |
| 101 | /// |
| 102 | /// // Set as complete. |
| 103 | /// completed_clone.store(true, Ordering::SeqCst); |
| 104 | /// }); |
| 105 | /// |
| 106 | /// // Inner task is detached, but will still complete. |
| 107 | /// }); |
| 108 | /// |
| 109 | /// // Give the task some time to complete. |
| 110 | /// sleep(Duration::from_millis(1000)); |
| 111 | /// |
| 112 | /// // Inner task completed even though it was detached. |
| 113 | /// assert_eq!(completed.load(Ordering::SeqCst), true); |
| 114 | /// ``` |
| 115 | pub struct Task<T> { |
| 116 | inner: Arc<Mutex<Inner<T>>>, |
| 117 | } |
| 118 | |
| 119 | struct Inner<T> { |
| 120 | result: Option<thread::Result<T>>, |
| 121 | waker: Option<Waker>, |
| 122 | } |
| 123 | |
| 124 | impl<T> Task<T> { |
| 125 | /// Create a new task from a closure. |
| 126 | pub(crate) fn from_closure<F>(closure: F) -> (Self, Coroutine) |
| 127 | where |
| 128 | F: FnOnce() -> T + Send + 'static, |
| 129 | T: Send + 'static, |
| 130 | { |
| 131 | let task = Self::pending(); |
| 132 | |
| 133 | let coroutine = Coroutine { |
| 134 | might_yield: false, |
| 135 | waker: crate::wakers::empty_waker(), |
| 136 | poller: Box::new(ClosurePoller { |
| 137 | closure: Some(closure), |
| 138 | result: None, |
| 139 | task: task.inner.clone(), |
| 140 | }), |
| 141 | }; |
| 142 | |
| 143 | (task, coroutine) |
| 144 | } |
| 145 | |
| 146 | /// Create a new asynchronous task from a future. |
| 147 | pub(crate) fn from_future<F>(future: F) -> (Self, Coroutine) |
| 148 | where |
| 149 | F: Future<Output = T> + Send + 'static, |
| 150 | T: Send + 'static, |
| 151 | { |
| 152 | let task = Self::pending(); |
| 153 | |
| 154 | let coroutine = Coroutine { |
| 155 | might_yield: true, |
| 156 | waker: crate::wakers::empty_waker(), |
| 157 | poller: Box::new(FuturePoller { |
| 158 | future, |
| 159 | result: None, |
| 160 | task: task.inner.clone(), |
| 161 | }), |
| 162 | }; |
| 163 | |
| 164 | (task, coroutine) |
| 165 | } |
| 166 | |
| 167 | fn pending() -> Self { |
| 168 | Self { |
| 169 | inner: Arc::new(Mutex::new(Inner { |
| 170 | result: None, |
| 171 | waker: None, |
| 172 | })), |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// Check if the task is done yet. |
| 177 | /// |
| 178 | /// If this method returns true, then calling [`join`](Task::join) will not |
| 179 | /// block. |
| 180 | pub fn is_done(&self) -> bool { |
| 181 | self.inner.lock().unwrap().result.is_some() |
| 182 | } |
| 183 | |
| 184 | /// Block the current thread until the task completes and return the value |
| 185 | /// the task produced. |
| 186 | /// |
| 187 | /// # Panics |
| 188 | /// |
| 189 | /// If the underlying task panics, the panic will propagate to this call. |
| 190 | pub fn join(self) -> T { |
| 191 | match self.join_catch() { |
| 192 | Ok(value) => value, |
| 193 | Err(e) => resume_unwind(e), |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | fn join_catch(self) -> thread::Result<T> { |
| 198 | let mut inner = self.inner.lock().unwrap(); |
| 199 | |
| 200 | if let Some(result) = inner.result.take() { |
| 201 | result |
| 202 | } else { |
| 203 | inner.waker = Some(crate::wakers::current_thread_waker()); |
| 204 | drop(inner); |
| 205 | |
| 206 | loop { |
| 207 | thread::park(); |
| 208 | |
| 209 | if let Some(result) = self.inner.lock().unwrap().result.take() { |
| 210 | break result; |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// Block the current thread until the task completes or a timeout is |
| 217 | /// reached. |
| 218 | /// |
| 219 | /// # Panics |
| 220 | /// |
| 221 | /// If the underlying task panics, the panic will propagate to this call. |
| 222 | pub fn join_timeout(self, timeout: Duration) -> Result<T, Self> { |
| 223 | self.join_deadline(Instant::now() + timeout) |
| 224 | } |
| 225 | |
| 226 | /// Block the current thread until the task completes or a timeout is |
| 227 | /// reached. |
| 228 | /// |
| 229 | /// # Panics |
| 230 | /// |
| 231 | /// If the underlying task panics, the panic will propagate to this call. |
| 232 | pub fn join_deadline(self, deadline: Instant) -> Result<T, Self> { |
| 233 | match { |
| 234 | let mut inner = self.inner.lock().unwrap(); |
| 235 | |
| 236 | if let Some(result) = inner.result.take() { |
| 237 | result |
| 238 | } else { |
| 239 | inner.waker = Some(crate::wakers::current_thread_waker()); |
| 240 | drop(inner); |
| 241 | |
| 242 | loop { |
| 243 | if let Some(timeout) = deadline.checked_duration_since(Instant::now()) { |
| 244 | thread::park_timeout(timeout); |
| 245 | } else { |
| 246 | return Err(self); |
| 247 | } |
| 248 | |
| 249 | if let Some(result) = self.inner.lock().unwrap().result.take() { |
| 250 | break result; |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | } { |
| 255 | Ok(value) => Ok(value), |
| 256 | Err(e) => resume_unwind(e), |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | impl<T> Future for Task<T> { |
| 262 | type Output = T; |
| 263 | |
| 264 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 265 | let mut inner = self.inner.lock().unwrap(); |
| 266 | |
| 267 | match inner.result.take() { |
| 268 | Some(Ok(value)) => Poll::Ready(value), |
| 269 | Some(Err(e)) => resume_unwind(e), |
| 270 | None => { |
| 271 | inner.waker = Some(cx.waker().clone()); |
| 272 | Poll::Pending |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | impl<T> fmt::Debug for Task<T> { |
| 279 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 280 | f.debug_struct("Task") |
| 281 | .field("done", &self.is_done()) |
| 282 | .finish() |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | /// The worker side of an allocated task, which provides methods for running the |
| 287 | /// underlying future to completion. |
| 288 | pub(crate) struct Coroutine { |
| 289 | might_yield: bool, |
| 290 | waker: Waker, |
| 291 | poller: Box<dyn CoroutinePoller>, |
| 292 | } |
| 293 | |
| 294 | impl Coroutine { |
| 295 | /// Determine whether this task might yield. This can be used for |
| 296 | /// optimizations if you know for certain a waker will never be used. |
| 297 | pub(crate) fn might_yield(&self) -> bool { |
| 298 | self.might_yield |
| 299 | } |
| 300 | |
| 301 | /// Get the unique memory address for this coroutine. |
| 302 | pub(crate) fn addr(&self) -> usize { |
| 303 | &*self.poller as *const dyn CoroutinePoller as *const () as usize |
| 304 | } |
| 305 | |
| 306 | /// Set the waker to use with this task. |
| 307 | pub(crate) fn set_waker(&mut self, waker: Waker) { |
| 308 | self.waker = waker; |
| 309 | } |
| 310 | |
| 311 | /// Run the coroutine until it yields or completes. |
| 312 | /// |
| 313 | /// Once this function returns `Complete` it should not be called again. Doing |
| 314 | /// so may panic, return weird results, or cause other problems. |
| 315 | pub(crate) fn run(&mut self) -> RunResult { |
| 316 | let mut cx = Context::from_waker(&self.waker); |
| 317 | self.poller.run(&mut cx) |
| 318 | } |
| 319 | |
| 320 | /// Complete the task with the final value produced by this coroutine and |
| 321 | /// notify any listeners on this task that the task's state has updated. |
| 322 | /// |
| 323 | /// Must not be called unless `run` has returned `Complete`. This method may |
| 324 | /// panic or cause other strange behavior otherwise. |
| 325 | /// |
| 326 | /// You must call this yourself when the task completes. It won't be called |
| 327 | /// automatically! |
| 328 | pub(crate) fn complete(mut self) { |
| 329 | self.poller.complete(); |
| 330 | } |
| 331 | |
| 332 | /// Unwrap the original closure the coroutine was created from. Panics if |
| 333 | /// the coroutine was not created from a closure. |
| 334 | pub(crate) fn into_inner_closure<F, T>(self) -> F |
| 335 | where |
| 336 | F: FnOnce() -> T + Send + 'static, |
| 337 | T: Send + 'static, |
| 338 | { |
| 339 | self |
| 340 | .poller |
| 341 | .into_any() |
| 342 | .downcast::<ClosurePoller<F, T>>() |
| 343 | .unwrap() |
| 344 | .closure |
| 345 | .take() |
| 346 | .unwrap() |
| 347 | } |
| 348 | |
| 349 | /// Unwrap the original future the coroutine was created from. Panics if the |
| 350 | /// coroutine was not created from a future. |
| 351 | pub(crate) fn into_inner_future<F, T>(self) -> F |
| 352 | where |
| 353 | F: Future<Output = T> + Send + 'static, |
| 354 | T: Send + 'static, |
| 355 | { |
| 356 | self |
| 357 | .poller |
| 358 | .into_any() |
| 359 | .downcast::<FuturePoller<F, T>>() |
| 360 | .unwrap() |
| 361 | .future |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 366 | pub(crate) enum RunResult { |
| 367 | /// The coroutine has yielded. You should call `run` on the coroutine again |
| 368 | /// once the waker associated with the coroutine is called. |
| 369 | Yield, |
| 370 | |
| 371 | /// The coroutine and its associated task has completed. You should call |
| 372 | /// [`Coroutine::complete`] to wake any consumers of the task to receive the |
| 373 | /// task result. |
| 374 | Complete { panicked: bool }, |
| 375 | } |
| 376 | |
| 377 | /// Inner implementation of a coroutine. This trait is used to erase the return |
| 378 | /// value from the coroutine type as well as to abstract over futures and |
| 379 | /// synchronous closures. Bundling all the required operations into this trait |
| 380 | /// also allows us to minimize the number of heap allocations per task. |
| 381 | trait CoroutinePoller: Send + 'static { |
| 382 | fn run(&mut self, cx: &mut Context) -> RunResult; |
| 383 | |
| 384 | fn complete(&mut self); |
| 385 | |
| 386 | fn into_any(self: Box<Self>) -> Box<dyn Any>; |
| 387 | } |
| 388 | |
| 389 | struct ClosurePoller<F, T> { |
| 390 | closure: Option<F>, |
| 391 | result: Option<thread::Result<T>>, |
| 392 | task: Arc<Mutex<Inner<T>>>, |
| 393 | } |
| 394 | |
| 395 | impl<F, T> CoroutinePoller for ClosurePoller<F, T> |
| 396 | where |
| 397 | F: FnOnce() -> T + Send + 'static, |
| 398 | T: Send + 'static, |
| 399 | { |
| 400 | fn run(&mut self, _cx: &mut Context) -> RunResult { |
| 401 | let closure = self |
| 402 | .closure |
| 403 | .take() |
| 404 | .expect("closure already ran to completion"); |
| 405 | let result = catch_unwind(AssertUnwindSafe(closure)); |
| 406 | let panicked = result.is_err(); |
| 407 | |
| 408 | self.result = Some(result); |
| 409 | |
| 410 | RunResult::Complete { |
| 411 | panicked, |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | fn complete(&mut self) { |
| 416 | if let Some(result) = self.result.take() { |
| 417 | let mut task = self.task.lock().unwrap(); |
| 418 | |
| 419 | task.result = Some(result); |
| 420 | |
| 421 | if let Some(waker) = task.waker.as_ref() { |
| 422 | waker.wake_by_ref(); |
| 423 | }; |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | fn into_any(self: Box<Self>) -> Box<dyn Any> { |
| 428 | self |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | struct FuturePoller<F, T> { |
| 433 | future: F, |
| 434 | result: Option<thread::Result<T>>, |
| 435 | task: Arc<Mutex<Inner<T>>>, |
| 436 | } |
| 437 | |
| 438 | impl<F, T> CoroutinePoller for FuturePoller<F, T> |
| 439 | where |
| 440 | F: Future<Output = T> + Send + 'static, |
| 441 | T: Send + 'static, |
| 442 | { |
| 443 | fn run(&mut self, cx: &mut Context) -> RunResult { |
| 444 | // Safety: This struct is only ever used inside a box, so we know that |
| 445 | // neither self nor this future will move. |
| 446 | let future = unsafe { Pin::new_unchecked(&mut self.future) }; |
| 447 | |
| 448 | match catch_unwind(AssertUnwindSafe(|| future.poll(cx))) { |
| 449 | Ok(Poll::Pending) => RunResult::Yield, |
| 450 | Ok(Poll::Ready(value)) => { |
| 451 | self.result = Some(Ok(value)); |
| 452 | |
| 453 | RunResult::Complete { |
| 454 | panicked: false, |
| 455 | } |
| 456 | } |
| 457 | Err(e) => { |
| 458 | self.result = Some(Err(e)); |
| 459 | |
| 460 | RunResult::Complete { |
| 461 | panicked: true, |
| 462 | } |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | fn complete(&mut self) { |
| 468 | if let Some(result) = self.result.take() { |
| 469 | let mut task = self.task.lock().unwrap(); |
| 470 | |
| 471 | task.result = Some(result); |
| 472 | |
| 473 | if let Some(waker) = task.waker.as_ref() { |
| 474 | waker.wake_by_ref(); |
| 475 | }; |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | fn into_any(self: Box<Self>) -> Box<dyn Any> { |
| 480 | self |
| 481 | } |
| 482 | } |