blob: 42a4024664960d910a783b98428514495323f131 [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 Glavina5c398cf2019-08-20 15:29:43 +020016/// When run, the task polls `future`. When woken up, it gets scheduled for running by the
17/// `schedule` 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///
Stjepan Glavina5c398cf2019-08-20 15:29:43 +020032/// // If the task gets woken up, it will be sent into this channel.
Stjepan Glavina1479e862019-08-12 20:18:51 +020033/// 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 Glavina5c398cf2019-08-20 15:29:43 +020060/// At any moment in time, there is at most one [`Task`] reference associated with a particular
61/// task. Running consumes the [`Task`] reference and polls its internal future. If the future is
62/// still pending after getting polled, the [`Task`] reference simply won't exist until a [`Waker`]
63/// notifies the task. If the future completes, its result becomes available to the [`JoinHandle`].
Stjepan Glavina1479e862019-08-12 20:18:51 +020064///
Stjepan Glavina5c398cf2019-08-20 15:29:43 +020065/// When a task is woken up, its [`Task`] reference is recreated and passed to the schedule
Stjepan Glavina7a8962b2019-08-16 11:25:25 +020066/// 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 Glavina5c398cf2019-08-20 15:29:43 +020069/// If the [`Task`] reference is dropped without getting run, the task is automatically cancelled.
70/// When cancelled, the task won't be scheduled again even if a [`Waker`] wakes it. It is possible
71/// for the [`JoinHandle`] to cancel while the [`Task`] reference exists, in which case an attempt
72/// to run 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
Stjepan Glavina5c398cf2019-08-20 15:29:43 +0200110 /// be woken up in order to be rescheduled and run again.
Stjepan Glavina1479e862019-08-12 20:18:51 +0200111 ///
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
Stjepan Glavina5c398cf2019-08-20 15:29:43 +0200117 /// [`catch_unwind`]. If a panic occurs, the task is automatically cancelled.
Stjepan Glavina1479e862019-08-12 20:18:51 +0200118 ///
Stjepan Glavina7a8962b2019-08-16 11:25:25 +0200119 /// [`JoinHandle`]: struct.JoinHandle.html
Stjepan Glavina1479e862019-08-12 20:18:51 +0200120 /// [`catch_unwind`]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
Stjepan Glavina1479e862019-08-12 20:18:51 +0200121 pub fn run(self) {
122 let ptr = self.raw_task.as_ptr();
123 let header = ptr as *const Header;
124 mem::forget(self);
125
126 unsafe {
127 ((*header).vtable.run)(ptr);
128 }
129 }
130
131 /// Cancels the task.
132 ///
133 /// When cancelled, the task won't be scheduled again even if a [`Waker`] wakes it. An attempt
Stjepan Glavina7a8962b2019-08-16 11:25:25 +0200134 /// to run it won't do anything.
Stjepan Glavina1479e862019-08-12 20:18:51 +0200135 ///
136 /// [`Waker`]: https://doc.rust-lang.org/std/task/struct.Waker.html
Stjepan Glavina1479e862019-08-12 20:18:51 +0200137 pub fn cancel(&self) {
138 let ptr = self.raw_task.as_ptr();
139 let header = ptr as *const Header;
140
141 unsafe {
142 (*header).cancel();
143 }
144 }
145
146 /// Returns a reference to the tag stored inside the task.
Stjepan Glavina1479e862019-08-12 20:18:51 +0200147 pub fn tag(&self) -> &T {
148 let offset = Header::offset_tag::<T>();
149 let ptr = self.raw_task.as_ptr();
150
151 unsafe {
152 let raw = (ptr as *mut u8).add(offset) as *const T;
153 &*raw
154 }
155 }
156}
157
158impl<T> Drop for Task<T> {
159 fn drop(&mut self) {
160 let ptr = self.raw_task.as_ptr();
161 let header = ptr as *const Header;
162
163 unsafe {
164 // Cancel the task.
165 (*header).cancel();
166
167 // Drop the future.
168 ((*header).vtable.drop_future)(ptr);
169
170 // Drop the task reference.
Stjepan Glavina5c398cf2019-08-20 15:29:43 +0200171 ((*header).vtable.drop_task)(ptr);
Stjepan Glavina1479e862019-08-12 20:18:51 +0200172 }
173 }
174}
175
176impl<T: fmt::Debug> fmt::Debug for Task<T> {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 let ptr = self.raw_task.as_ptr();
179 let header = ptr as *const Header;
180
181 f.debug_struct("Task")
182 .field("header", unsafe { &(*header) })
183 .field("tag", self.tag())
184 .finish()
185 }
186}