blob: 9097f44d0b471c7e0f9a9f722dc98c0893f38a5f [file] [log] [blame]
Stjepan Glavina1479e862019-08-12 20:18:51 +02001use std::fmt;
2use std::future::Future;
3use std::marker::PhantomData;
4use std::mem;
5use std::ptr::NonNull;
6
7use crate::header::Header;
8use crate::raw::RawTask;
9use crate::JoinHandle;
10
11/// Creates a new task.
12///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +020013/// This constructor returns a [`Task`] reference that runs the future and a [`JoinHandle`] that
Stjepan Glavina1479e862019-08-12 20:18:51 +020014/// awaits its result.
15///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +020016/// When run, the task polls `future`. When woken, it gets scheduled for running by the `schedule`
17/// function. Argument `tag` is an arbitrary piece of data stored inside the task.
Stjepan Glavina1479e862019-08-12 20:18:51 +020018///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +020019/// [`Task`]: struct.Task.html
20/// [`JoinHandle`]: struct.JoinHandle.html
Stjepan Glavina1479e862019-08-12 20:18:51 +020021///
22/// # Examples
23///
24/// ```
Stjepan Glavina1479e862019-08-12 20:18:51 +020025/// use crossbeam::channel;
26///
27/// // The future inside the task.
28/// let future = async {
29/// println!("Hello, world!");
30/// };
31///
32/// // If the task gets woken, it will be sent into this channel.
33/// let (s, r) = channel::unbounded();
34/// let schedule = move |task| s.send(task).unwrap();
35///
36/// // Create a task with the future and the schedule function.
37/// let (task, handle) = async_task::spawn(future, schedule, ());
38/// ```
Stjepan Glavina1479e862019-08-12 20:18:51 +020039pub fn spawn<F, R, S, T>(future: F, schedule: S, tag: T) -> (Task<T>, JoinHandle<R, T>)
40where
41 F: Future<Output = R> + Send + 'static,
42 R: Send + 'static,
43 S: Fn(Task<T>) + Send + Sync + 'static,
44 T: Send + Sync + 'static,
45{
46 let raw_task = RawTask::<F, R, S, T>::allocate(tag, future, schedule);
47 let task = Task {
48 raw_task,
49 _marker: PhantomData,
50 };
51 let handle = JoinHandle {
52 raw_task,
53 _marker: PhantomData,
54 };
55 (task, handle)
56}
57
Stjepan Glavina7a8962b2019-08-16 11:25:25 +020058/// A task reference that runs its future.
Stjepan Glavina1479e862019-08-12 20:18:51 +020059///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +020060/// The [`Task`] reference "owns" the task itself and is able to run it. Running consumes the
61/// [`Task`] reference and polls its internal future. If the future is still pending after getting
62/// polled, the [`Task`] reference simply won't exist until a [`Waker`] notifies the task. If the
63/// future completes, its result becomes available to the [`JoinHandle`].
Stjepan Glavina1479e862019-08-12 20:18:51 +020064///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +020065/// When the task is woken, the [`Task`] reference is recreated and passed to the schedule
66/// function. In most executors, scheduling simply pushes the [`Task`] reference into a queue of
67/// runnable tasks.
Stjepan Glavina1479e862019-08-12 20:18:51 +020068///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +020069/// If the [`Task`] reference is dropped without being run, the task is cancelled. When cancelled,
70/// the task won't be scheduled again even if a [`Waker`] wakes it. It is possible for the
71/// [`JoinHandle`] to cancel while the [`Task`] reference exists, in which case an attempt to run
72/// the task won't do anything.
Stjepan Glavina1479e862019-08-12 20:18:51 +020073///
74/// [`run()`]: struct.Task.html#method.run
Stjepan Glavina1479e862019-08-12 20:18:51 +020075/// [`JoinHandle`]: struct.JoinHandle.html
76/// [`Task`]: struct.Task.html
Stjepan Glavina1479e862019-08-12 20:18:51 +020077/// [`Waker`]: https://doc.rust-lang.org/std/task/struct.Waker.html
Stjepan Glavina1479e862019-08-12 20:18:51 +020078pub struct Task<T> {
79 /// A pointer to the heap-allocated task.
80 pub(crate) raw_task: NonNull<()>,
81
82 /// A marker capturing the generic type `T`.
83 pub(crate) _marker: PhantomData<T>,
84}
85
86unsafe impl<T> Send for Task<T> {}
87unsafe impl<T> Sync for Task<T> {}
88
89impl<T> Task<T> {
90 /// Schedules the task.
91 ///
92 /// This is a convenience method that simply reschedules the task by passing it to its schedule
93 /// function.
94 ///
95 /// If the task is cancelled, this method won't do anything.
Stjepan Glavina1479e862019-08-12 20:18:51 +020096 pub fn schedule(self) {
97 let ptr = self.raw_task.as_ptr();
98 let header = ptr as *const Header;
99 mem::forget(self);
100
101 unsafe {
102 ((*header).vtable.schedule)(ptr);
103 }
104 }
105
106 /// Runs the task.
107 ///
108 /// This method polls the task's future. If the future completes, its result will become
109 /// available to the [`JoinHandle`]. And if the future is still pending, the task will have to
110 /// be woken in order to be rescheduled and then run again.
111 ///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +0200112 /// If the task was cancelled by a [`JoinHandle`] before it gets run, then this method won't do
113 /// anything.
Stjepan Glavina1479e862019-08-12 20:18:51 +0200114 ///
115 /// It is possible that polling the future panics, in which case the panic will be propagated
116 /// into the caller. It is advised that invocations of this method are wrapped inside
117 /// [`catch_unwind`].
118 ///
119 /// If a panic occurs, the task is automatically cancelled.
120 ///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +0200121 /// [`JoinHandle`]: struct.JoinHandle.html
Stjepan Glavina1479e862019-08-12 20:18:51 +0200122 /// [`catch_unwind`]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
Stjepan Glavina1479e862019-08-12 20:18:51 +0200123 pub fn run(self) {
124 let ptr = self.raw_task.as_ptr();
125 let header = ptr as *const Header;
126 mem::forget(self);
127
128 unsafe {
129 ((*header).vtable.run)(ptr);
130 }
131 }
132
133 /// Cancels the task.
134 ///
135 /// When cancelled, the task won't be scheduled again even if a [`Waker`] wakes it. An attempt
Stjepan Glavina7a8962b2019-08-16 11:25:25 +0200136 /// to run it won't do anything.
Stjepan Glavina1479e862019-08-12 20:18:51 +0200137 ///
138 /// [`Waker`]: https://doc.rust-lang.org/std/task/struct.Waker.html
Stjepan Glavina1479e862019-08-12 20:18:51 +0200139 pub fn cancel(&self) {
140 let ptr = self.raw_task.as_ptr();
141 let header = ptr as *const Header;
142
143 unsafe {
144 (*header).cancel();
145 }
146 }
147
148 /// Returns a reference to the tag stored inside the task.
Stjepan Glavina1479e862019-08-12 20:18:51 +0200149 pub fn tag(&self) -> &T {
150 let offset = Header::offset_tag::<T>();
151 let ptr = self.raw_task.as_ptr();
152
153 unsafe {
154 let raw = (ptr as *mut u8).add(offset) as *const T;
155 &*raw
156 }
157 }
158}
159
160impl<T> Drop for Task<T> {
161 fn drop(&mut self) {
162 let ptr = self.raw_task.as_ptr();
163 let header = ptr as *const Header;
164
165 unsafe {
166 // Cancel the task.
167 (*header).cancel();
168
169 // Drop the future.
170 ((*header).vtable.drop_future)(ptr);
171
172 // Drop the task reference.
173 ((*header).vtable.decrement)(ptr);
174 }
175 }
176}
177
178impl<T: fmt::Debug> fmt::Debug for Task<T> {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 let ptr = self.raw_task.as_ptr();
181 let header = ptr as *const Header;
182
183 f.debug_struct("Task")
184 .field("header", unsafe { &(*header) })
185 .field("tag", self.tag())
186 .finish()
187 }
188}