Stjepan Glavina | 921e8a0 | 2020-01-06 14:31:28 -0600 | [diff] [blame] | 1 | use core::fmt; |
| 2 | use core::future::Future; |
| 3 | use core::marker::PhantomData; |
| 4 | use core::mem::{self, ManuallyDrop}; |
| 5 | use core::pin::Pin; |
| 6 | use core::ptr::NonNull; |
Stjepan Glavina | af051a5 | 2020-01-06 15:25:52 -0600 | [diff] [blame] | 7 | use core::task::{Context, Poll, Waker}; |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 8 | |
| 9 | use crate::header::Header; |
| 10 | use crate::raw::RawTask; |
| 11 | use crate::JoinHandle; |
| 12 | |
| 13 | /// Creates a new task. |
| 14 | /// |
Stjepan Glavina | 7a8962b | 2019-08-16 11:25:25 +0200 | [diff] [blame] | 15 | /// This constructor returns a [`Task`] reference that runs the future and a [`JoinHandle`] that |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 16 | /// awaits its result. |
| 17 | /// |
Stjepan Glavina | 5c398cf | 2019-08-20 15:29:43 +0200 | [diff] [blame] | 18 | /// When run, the task polls `future`. When woken up, it gets scheduled for running by the |
| 19 | /// `schedule` function. Argument `tag` is an arbitrary piece of data stored inside the task. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 20 | /// |
Stjepan Glavina | 951d971 | 2019-11-25 18:47:16 +0100 | [diff] [blame] | 21 | /// The schedule function should not attempt to run the task nor to drop it. Instead, it should |
| 22 | /// push the task into some kind of queue so that it can be processed later. |
| 23 | /// |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 24 | /// If you need to spawn a future that does not implement [`Send`], consider using the |
| 25 | /// [`spawn_local`] function instead. |
| 26 | /// |
Stjepan Glavina | 7a8962b | 2019-08-16 11:25:25 +0200 | [diff] [blame] | 27 | /// [`Task`]: struct.Task.html |
| 28 | /// [`JoinHandle`]: struct.JoinHandle.html |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 29 | /// [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html |
| 30 | /// [`spawn_local`]: fn.spawn_local.html |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 31 | /// |
| 32 | /// # Examples |
| 33 | /// |
| 34 | /// ``` |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 35 | /// use crossbeam::channel; |
| 36 | /// |
| 37 | /// // The future inside the task. |
| 38 | /// let future = async { |
| 39 | /// println!("Hello, world!"); |
| 40 | /// }; |
| 41 | /// |
Stjepan Glavina | 5c398cf | 2019-08-20 15:29:43 +0200 | [diff] [blame] | 42 | /// // If the task gets woken up, it will be sent into this channel. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 43 | /// let (s, r) = channel::unbounded(); |
| 44 | /// let schedule = move |task| s.send(task).unwrap(); |
| 45 | /// |
| 46 | /// // Create a task with the future and the schedule function. |
| 47 | /// let (task, handle) = async_task::spawn(future, schedule, ()); |
| 48 | /// ``` |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 49 | pub fn spawn<F, R, S, T>(future: F, schedule: S, tag: T) -> (Task<T>, JoinHandle<R, T>) |
| 50 | where |
| 51 | F: Future<Output = R> + Send + 'static, |
| 52 | R: Send + 'static, |
| 53 | S: Fn(Task<T>) + Send + Sync + 'static, |
| 54 | T: Send + Sync + 'static, |
| 55 | { |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 56 | let raw_task = RawTask::<F, R, S, T>::allocate(future, schedule, tag); |
| 57 | let task = Task { |
| 58 | raw_task, |
| 59 | _marker: PhantomData, |
| 60 | }; |
| 61 | let handle = JoinHandle { |
| 62 | raw_task, |
| 63 | _marker: PhantomData, |
| 64 | }; |
| 65 | (task, handle) |
| 66 | } |
| 67 | |
| 68 | /// Creates a new local task. |
| 69 | /// |
| 70 | /// This constructor returns a [`Task`] reference that runs the future and a [`JoinHandle`] that |
| 71 | /// awaits its result. |
| 72 | /// |
| 73 | /// When run, the task polls `future`. When woken up, it gets scheduled for running by the |
| 74 | /// `schedule` function. Argument `tag` is an arbitrary piece of data stored inside the task. |
| 75 | /// |
Stjepan Glavina | 951d971 | 2019-11-25 18:47:16 +0100 | [diff] [blame] | 76 | /// The schedule function should not attempt to run the task nor to drop it. Instead, it should |
| 77 | /// push the task into some kind of queue so that it can be processed later. |
| 78 | /// |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 79 | /// Unlike [`spawn`], this function does not require the future to implement [`Send`]. If the |
| 80 | /// [`Task`] reference is run or dropped on a thread it was not created on, a panic will occur. |
| 81 | /// |
| 82 | /// [`Task`]: struct.Task.html |
| 83 | /// [`JoinHandle`]: struct.JoinHandle.html |
| 84 | /// [`spawn`]: fn.spawn.html |
| 85 | /// [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html |
| 86 | /// |
| 87 | /// # Examples |
| 88 | /// |
| 89 | /// ``` |
| 90 | /// use crossbeam::channel; |
| 91 | /// |
| 92 | /// // The future inside the task. |
| 93 | /// let future = async { |
| 94 | /// println!("Hello, world!"); |
| 95 | /// }; |
| 96 | /// |
| 97 | /// // If the task gets woken up, it will be sent into this channel. |
| 98 | /// let (s, r) = channel::unbounded(); |
| 99 | /// let schedule = move |task| s.send(task).unwrap(); |
| 100 | /// |
| 101 | /// // Create a task with the future and the schedule function. |
| 102 | /// let (task, handle) = async_task::spawn_local(future, schedule, ()); |
| 103 | /// ``` |
Stjepan Glavina | 7e7d19c | 2020-01-07 22:45:13 +0100 | [diff] [blame] | 104 | #[cfg(any(unix, windows))] |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 105 | pub fn spawn_local<F, R, S, T>(future: F, schedule: S, tag: T) -> (Task<T>, JoinHandle<R, T>) |
| 106 | where |
| 107 | F: Future<Output = R> + 'static, |
| 108 | R: 'static, |
| 109 | S: Fn(Task<T>) + Send + Sync + 'static, |
| 110 | T: Send + Sync + 'static, |
| 111 | { |
Stjepan Glavina | 921e8a0 | 2020-01-06 14:31:28 -0600 | [diff] [blame] | 112 | #[cfg(unix)] |
| 113 | #[inline] |
| 114 | fn thread_id() -> usize { |
| 115 | unsafe { libc::pthread_self() as usize } |
| 116 | } |
| 117 | |
| 118 | #[cfg(windows)] |
| 119 | #[inline] |
| 120 | fn thread_id() -> usize { |
| 121 | unsafe { winapi::um::processthreadsapi::GetCurrentThreadId() as usize } |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 122 | } |
| 123 | |
| 124 | struct Checked<F> { |
Stjepan Glavina | 921e8a0 | 2020-01-06 14:31:28 -0600 | [diff] [blame] | 125 | id: usize, |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 126 | inner: ManuallyDrop<F>, |
| 127 | } |
| 128 | |
| 129 | impl<F> Drop for Checked<F> { |
| 130 | fn drop(&mut self) { |
Stjepan Glavina | 921e8a0 | 2020-01-06 14:31:28 -0600 | [diff] [blame] | 131 | assert!( |
| 132 | self.id == thread_id(), |
| 133 | "local task dropped by a thread that didn't spawn it" |
| 134 | ); |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 135 | unsafe { |
| 136 | ManuallyDrop::drop(&mut self.inner); |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | impl<F: Future> Future for Checked<F> { |
| 142 | type Output = F::Output; |
| 143 | |
| 144 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
Stjepan Glavina | 921e8a0 | 2020-01-06 14:31:28 -0600 | [diff] [blame] | 145 | assert!( |
| 146 | self.id == thread_id(), |
| 147 | "local task polled by a thread that didn't spawn it" |
| 148 | ); |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 149 | unsafe { self.map_unchecked_mut(|c| &mut *c.inner).poll(cx) } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | let future = Checked { |
Stjepan Glavina | 921e8a0 | 2020-01-06 14:31:28 -0600 | [diff] [blame] | 154 | id: thread_id(), |
Stjepan Glavina | fcfa4ab | 2019-11-25 18:39:17 +0100 | [diff] [blame] | 155 | inner: ManuallyDrop::new(future), |
| 156 | }; |
| 157 | |
| 158 | let raw_task = RawTask::<_, R, S, T>::allocate(future, schedule, tag); |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 159 | let task = Task { |
| 160 | raw_task, |
| 161 | _marker: PhantomData, |
| 162 | }; |
| 163 | let handle = JoinHandle { |
| 164 | raw_task, |
| 165 | _marker: PhantomData, |
| 166 | }; |
| 167 | (task, handle) |
| 168 | } |
| 169 | |
Stjepan Glavina | 7a8962b | 2019-08-16 11:25:25 +0200 | [diff] [blame] | 170 | /// A task reference that runs its future. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 171 | /// |
Stjepan Glavina | 5c398cf | 2019-08-20 15:29:43 +0200 | [diff] [blame] | 172 | /// At any moment in time, there is at most one [`Task`] reference associated with a particular |
| 173 | /// task. Running consumes the [`Task`] reference and polls its internal future. If the future is |
| 174 | /// still pending after getting polled, the [`Task`] reference simply won't exist until a [`Waker`] |
| 175 | /// notifies the task. If the future completes, its result becomes available to the [`JoinHandle`]. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 176 | /// |
Stjepan Glavina | 5c398cf | 2019-08-20 15:29:43 +0200 | [diff] [blame] | 177 | /// When a task is woken up, its [`Task`] reference is recreated and passed to the schedule |
Stjepan Glavina | 7a8962b | 2019-08-16 11:25:25 +0200 | [diff] [blame] | 178 | /// function. In most executors, scheduling simply pushes the [`Task`] reference into a queue of |
| 179 | /// runnable tasks. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 180 | /// |
Stjepan Glavina | 5c398cf | 2019-08-20 15:29:43 +0200 | [diff] [blame] | 181 | /// If the [`Task`] reference is dropped without getting run, the task is automatically cancelled. |
| 182 | /// When cancelled, the task won't be scheduled again even if a [`Waker`] wakes it. It is possible |
| 183 | /// for the [`JoinHandle`] to cancel while the [`Task`] reference exists, in which case an attempt |
| 184 | /// to run the task won't do anything. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 185 | /// |
| 186 | /// [`run()`]: struct.Task.html#method.run |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 187 | /// [`JoinHandle`]: struct.JoinHandle.html |
| 188 | /// [`Task`]: struct.Task.html |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 189 | /// [`Waker`]: https://doc.rust-lang.org/std/task/struct.Waker.html |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 190 | pub struct Task<T> { |
| 191 | /// A pointer to the heap-allocated task. |
| 192 | pub(crate) raw_task: NonNull<()>, |
| 193 | |
| 194 | /// A marker capturing the generic type `T`. |
| 195 | pub(crate) _marker: PhantomData<T>, |
| 196 | } |
| 197 | |
| 198 | unsafe impl<T> Send for Task<T> {} |
| 199 | unsafe impl<T> Sync for Task<T> {} |
| 200 | |
| 201 | impl<T> Task<T> { |
| 202 | /// Schedules the task. |
| 203 | /// |
| 204 | /// This is a convenience method that simply reschedules the task by passing it to its schedule |
| 205 | /// function. |
| 206 | /// |
| 207 | /// If the task is cancelled, this method won't do anything. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 208 | pub fn schedule(self) { |
| 209 | let ptr = self.raw_task.as_ptr(); |
| 210 | let header = ptr as *const Header; |
| 211 | mem::forget(self); |
| 212 | |
| 213 | unsafe { |
| 214 | ((*header).vtable.schedule)(ptr); |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | /// Runs the task. |
| 219 | /// |
Stjepan Glavina | 9405905 | 2020-04-12 19:46:20 +0200 | [diff] [blame^] | 220 | /// Returns `true` if the task was woken while running, in which case it gets rescheduled at |
| 221 | /// the end of this method invocation. |
| 222 | /// |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 223 | /// This method polls the task's future. If the future completes, its result will become |
| 224 | /// available to the [`JoinHandle`]. And if the future is still pending, the task will have to |
Stjepan Glavina | 5c398cf | 2019-08-20 15:29:43 +0200 | [diff] [blame] | 225 | /// be woken up in order to be rescheduled and run again. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 226 | /// |
Stjepan Glavina | 7a8962b | 2019-08-16 11:25:25 +0200 | [diff] [blame] | 227 | /// If the task was cancelled by a [`JoinHandle`] before it gets run, then this method won't do |
| 228 | /// anything. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 229 | /// |
| 230 | /// It is possible that polling the future panics, in which case the panic will be propagated |
| 231 | /// into the caller. It is advised that invocations of this method are wrapped inside |
Stjepan Glavina | 5c398cf | 2019-08-20 15:29:43 +0200 | [diff] [blame] | 232 | /// [`catch_unwind`]. If a panic occurs, the task is automatically cancelled. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 233 | /// |
Stjepan Glavina | 7a8962b | 2019-08-16 11:25:25 +0200 | [diff] [blame] | 234 | /// [`JoinHandle`]: struct.JoinHandle.html |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 235 | /// [`catch_unwind`]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html |
Stjepan Glavina | 9405905 | 2020-04-12 19:46:20 +0200 | [diff] [blame^] | 236 | pub fn run(self) -> bool { |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 237 | let ptr = self.raw_task.as_ptr(); |
| 238 | let header = ptr as *const Header; |
| 239 | mem::forget(self); |
| 240 | |
| 241 | unsafe { |
Stjepan Glavina | 9405905 | 2020-04-12 19:46:20 +0200 | [diff] [blame^] | 242 | ((*header).vtable.run)(ptr) |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 243 | } |
| 244 | } |
| 245 | |
| 246 | /// Cancels the task. |
| 247 | /// |
| 248 | /// When cancelled, the task won't be scheduled again even if a [`Waker`] wakes it. An attempt |
Stjepan Glavina | 7a8962b | 2019-08-16 11:25:25 +0200 | [diff] [blame] | 249 | /// to run it won't do anything. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 250 | /// |
| 251 | /// [`Waker`]: https://doc.rust-lang.org/std/task/struct.Waker.html |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 252 | pub fn cancel(&self) { |
| 253 | let ptr = self.raw_task.as_ptr(); |
| 254 | let header = ptr as *const Header; |
| 255 | |
| 256 | unsafe { |
| 257 | (*header).cancel(); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | /// Returns a reference to the tag stored inside the task. |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 262 | pub fn tag(&self) -> &T { |
| 263 | let offset = Header::offset_tag::<T>(); |
| 264 | let ptr = self.raw_task.as_ptr(); |
| 265 | |
| 266 | unsafe { |
| 267 | let raw = (ptr as *mut u8).add(offset) as *const T; |
| 268 | &*raw |
| 269 | } |
| 270 | } |
Stjepan Glavina | af051a5 | 2020-01-06 15:25:52 -0600 | [diff] [blame] | 271 | |
| 272 | /// Converts this task into a raw pointer to the tag. |
| 273 | pub fn into_raw(self) -> *const T { |
| 274 | let offset = Header::offset_tag::<T>(); |
| 275 | let ptr = self.raw_task.as_ptr(); |
| 276 | mem::forget(self); |
| 277 | |
| 278 | unsafe { (ptr as *mut u8).add(offset) as *const T } |
| 279 | } |
| 280 | |
| 281 | /// Converts a raw pointer to the tag into a task. |
| 282 | /// |
| 283 | /// This method should only be used with raw pointers returned from [`into_raw`]. |
| 284 | /// |
| 285 | /// [`into_raw`]: #method.into_raw |
| 286 | pub unsafe fn from_raw(raw: *const T) -> Task<T> { |
| 287 | let offset = Header::offset_tag::<T>(); |
| 288 | let ptr = (raw as *mut u8).sub(offset) as *mut (); |
| 289 | |
| 290 | Task { |
| 291 | raw_task: NonNull::new_unchecked(ptr), |
| 292 | _marker: PhantomData, |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// Returns a waker associated with this task. |
| 297 | pub fn waker(&self) -> Waker { |
| 298 | let ptr = self.raw_task.as_ptr(); |
| 299 | let header = ptr as *const Header; |
| 300 | |
| 301 | unsafe { |
| 302 | let raw_waker = ((*header).vtable.clone_waker)(ptr); |
| 303 | Waker::from_raw(raw_waker) |
| 304 | } |
| 305 | } |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 306 | } |
| 307 | |
| 308 | impl<T> Drop for Task<T> { |
| 309 | fn drop(&mut self) { |
| 310 | let ptr = self.raw_task.as_ptr(); |
| 311 | let header = ptr as *const Header; |
| 312 | |
| 313 | unsafe { |
| 314 | // Cancel the task. |
| 315 | (*header).cancel(); |
| 316 | |
| 317 | // Drop the future. |
| 318 | ((*header).vtable.drop_future)(ptr); |
| 319 | |
| 320 | // Drop the task reference. |
Stjepan Glavina | 5c398cf | 2019-08-20 15:29:43 +0200 | [diff] [blame] | 321 | ((*header).vtable.drop_task)(ptr); |
Stjepan Glavina | 1479e86 | 2019-08-12 20:18:51 +0200 | [diff] [blame] | 322 | } |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | impl<T: fmt::Debug> fmt::Debug for Task<T> { |
| 327 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 328 | let ptr = self.raw_task.as_ptr(); |
| 329 | let header = ptr as *const Header; |
| 330 | |
| 331 | f.debug_struct("Task") |
| 332 | .field("header", unsafe { &(*header) }) |
| 333 | .field("tag", self.tag()) |
| 334 | .finish() |
| 335 | } |
| 336 | } |