about summary refs log tree commit diff
path: root/src/libcore/task
diff options
context:
space:
mode:
authorMatthias Einwag <matthias.einwag@live.com>2019-01-29 19:02:42 -0800
committerMatthias Einwag <matthias.einwag@live.com>2019-02-03 13:46:53 -0800
commitd9a4b22d3291913a8f2158a1b7c195bc30c9286e (patch)
treecfa2cc014dc500634727555d9fc16b818e2c10f0 /src/libcore/task
parent4f4f4a40b6c7bcb6fa07ee6575e8a9759ba08922 (diff)
Update the future/task API
This change updates the future and task API as discussed in the stabilization RFC at https://github.com/rust-lang/rfcs/pull/2592.

Changes:
- Replacing UnsafeWake with RawWaker and RawWakerVtable
- Removal of LocalWaker
- Removal of Arc-based Wake trait
Diffstat (limited to 'src/libcore/task')
-rw-r--r--src/libcore/task/mod.rs2
-rw-r--r--src/libcore/task/wake.rs316
2 files changed, 83 insertions, 235 deletions
diff --git a/src/libcore/task/mod.rs b/src/libcore/task/mod.rs
index 9552e53ebf8..9b8f5981162 100644
--- a/src/libcore/task/mod.rs
+++ b/src/libcore/task/mod.rs
@@ -8,4 +8,4 @@ mod poll;
 pub use self::poll::Poll;
 
 mod wake;
-pub use self::wake::{Waker, LocalWaker, UnsafeWake};
+pub use self::wake::{Waker, RawWaker, RawWakerVTable};
diff --git a/src/libcore/task/wake.rs b/src/libcore/task/wake.rs
index 3f7098f1ef9..bb91bf2ecfb 100644
--- a/src/libcore/task/wake.rs
+++ b/src/libcore/task/wake.rs
@@ -4,16 +4,76 @@
 
 use fmt;
 use marker::Unpin;
-use ptr::NonNull;
+
+/// A `RawWaker` allows the implementor of a task executor to create a `Waker`
+/// which provides customized wakeup behavior.
+///
+/// It consists of a data pointer and a virtual function pointer table (vtable) that
+/// customizes the behavior of the `RawWaker`.
+#[derive(PartialEq)]
+pub struct RawWaker {
+    /// A data pointer, which can be used to store arbitrary data as required
+    /// by the executor. This could be e.g. a type-erased pointer to an `Arc`
+    /// that is associated with the task.
+    /// The value of this field gets passed to all functions that are part of
+    /// the vtable as first parameter.
+    pub data: *const (),
+    /// Virtual function pointer table that customizes the behavior of this waker.
+    pub vtable: &'static RawWakerVTable,
+}
+
+impl fmt::Debug for RawWaker {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        f.debug_struct("RawWaker")
+            .finish()
+    }
+}
+
+/// A virtual function pointer table (vtable) that specifies the behavior
+/// of a `RawWaker`.
+///
+/// The pointer passed to all functions inside the vtable is the `data` pointer
+/// from the enclosing `RawWaker` object.
+#[derive(PartialEq, Copy, Clone)]
+pub struct RawWakerVTable {
+    /// This function will be called when the `RawWaker` gets cloned, e.g. when
+    /// the `Waker` in which the `RawWaker` is stored gets cloned.
+    ///
+    /// The implementation of this function must retain all resources that are
+    /// required for this additional instance of a `RawWaker` and associated
+    /// task. Calling `wake` on the resulting `RawWaker` should result in a wakeup
+    /// of the same task that would have been awoken by the original `RawWaker`.
+    pub clone: unsafe fn(*const ()) -> RawWaker,
+
+    /// This function will be called when `wake` is called on the `Waker`.
+    /// It must wake up the task associated with this `RawWaker`.
+    pub wake: unsafe fn(*const ()),
+
+    /// This function gets called when a `RawWaker` gets dropped.
+    ///
+    /// The implementation of this function must make sure to release any
+    /// resources that are associated with this instance of a `RawWaker` and
+    /// associated task.
+    pub drop_fn: unsafe fn(*const ()),
+}
+
+impl fmt::Debug for RawWakerVTable {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        f.debug_struct("RawWakerVTable")
+            .finish()
+    }
+}
 
 /// A `Waker` is a handle for waking up a task by notifying its executor that it
 /// is ready to be run.
 ///
-/// This handle contains a trait object pointing to an instance of the `UnsafeWake`
-/// trait, allowing notifications to get routed through it.
+/// This handle encapsulates a `RawWaker` instance, which defines the
+/// executor-specific wakeup behavior.
+///
+/// Implements `Clone`, `Send`, and `Sync`.
 #[repr(transparent)]
 pub struct Waker {
-    inner: NonNull<dyn UnsafeWake>,
+    waker: RawWaker,
 }
 
 impl Unpin for Waker {}
@@ -21,264 +81,52 @@ unsafe impl Send for Waker {}
 unsafe impl Sync for Waker {}
 
 impl Waker {
-    /// Constructs a new `Waker` directly.
-    ///
-    /// Note that most code will not need to call this. Implementers of the
-    /// `UnsafeWake` trait will typically provide a wrapper that calls this
-    /// but you otherwise shouldn't call it directly.
-    ///
-    /// If you're working with the standard library then it's recommended to
-    /// use the `Waker::from` function instead which works with the safe
-    /// `Arc` type and the safe `Wake` trait.
-    #[inline]
-    pub unsafe fn new(inner: NonNull<dyn UnsafeWake>) -> Self {
-        Waker { inner }
-    }
-
     /// Wake up the task associated with this `Waker`.
-    #[inline]
     pub fn wake(&self) {
-        unsafe { self.inner.as_ref().wake() }
+        // The actual wakeup call is delegated through a virtual function call
+        // to the implementation which is defined by the executor.
+        unsafe { (self.waker.vtable.wake)(self.waker.data) }
     }
 
-    /// Returns whether or not this `Waker` and `other` awaken the same task.
+    /// Returns whether or not this `Waker` and other `Waker` have awaken the same task.
     ///
     /// This function works on a best-effort basis, and may return false even
     /// when the `Waker`s would awaken the same task. However, if this function
-    /// returns true, it is guaranteed that the `Waker`s will awaken the same
-    /// task.
+    /// returns `true`, it is guaranteed that the `Waker`s will awaken the same task.
     ///
     /// This function is primarily used for optimization purposes.
-    #[inline]
     pub fn will_wake(&self, other: &Waker) -> bool {
-        self.inner == other.inner
+        self.waker == other.waker
     }
 
-    /// Returns whether or not this `Waker` and `other` `LocalWaker` awaken
-    /// the same task.
-    ///
-    /// This function works on a best-effort basis, and may return false even
-    /// when the `Waker`s would awaken the same task. However, if this function
-    /// returns true, it is guaranteed that the `Waker`s will awaken the same
-    /// task.
+    /// Creates a new `Waker` from `RawWaker`.
     ///
-    /// This function is primarily used for optimization purposes.
-    #[inline]
-    pub fn will_wake_local(&self, other: &LocalWaker) -> bool {
-        self.will_wake(&other.0)
+    /// The method cannot check whether `RawWaker` fulfills the required API
+    /// contract to make it usable for `Waker` and is therefore unsafe.
+    pub unsafe fn new_unchecked(waker: RawWaker) -> Waker {
+        Waker {
+            waker: waker,
+        }
     }
 }
 
 impl Clone for Waker {
-    #[inline]
     fn clone(&self) -> Self {
-        unsafe {
-            self.inner.as_ref().clone_raw()
+        Waker {
+            waker: unsafe { (self.waker.vtable.clone)(self.waker.data) },
         }
     }
 }
 
-impl fmt::Debug for Waker {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        f.debug_struct("Waker")
-            .finish()
-    }
-}
-
 impl Drop for Waker {
-    #[inline]
     fn drop(&mut self) {
-        unsafe {
-            self.inner.as_ref().drop_raw()
-        }
+        unsafe { (self.waker.vtable.drop_fn)(self.waker.data) }
     }
 }
 
-/// A `LocalWaker` is a handle for waking up a task by notifying its executor that it
-/// is ready to be run.
-///
-/// This is similar to the `Waker` type, but cannot be sent across threads.
-/// Task executors can use this type to implement more optimized single-threaded wakeup
-/// behavior.
-#[repr(transparent)]
-#[derive(Clone)]
-pub struct LocalWaker(Waker);
-
-impl Unpin for LocalWaker {}
-impl !Send for LocalWaker {}
-impl !Sync for LocalWaker {}
-
-impl LocalWaker {
-    /// Constructs a new `LocalWaker` directly.
-    ///
-    /// Note that most code will not need to call this. Implementers of the
-    /// `UnsafeWake` trait will typically provide a wrapper that calls this
-    /// but you otherwise shouldn't call it directly.
-    ///
-    /// If you're working with the standard library then it's recommended to
-    /// use the `local_waker_from_nonlocal` or `local_waker` to convert a `Waker`
-    /// into a `LocalWaker`.
-    ///
-    /// For this function to be used safely, it must be sound to call `inner.wake_local()`
-    /// on the current thread.
-    #[inline]
-    pub unsafe fn new(inner: NonNull<dyn UnsafeWake>) -> Self {
-        LocalWaker(Waker::new(inner))
-    }
-
-    /// Borrows this `LocalWaker` as a `Waker`.
-    ///
-    /// `Waker` is nearly identical to `LocalWaker`, but is threadsafe
-    /// (implements `Send` and `Sync`).
-    #[inline]
-    pub fn as_waker(&self) -> &Waker {
-        &self.0
-    }
-
-    /// Converts this `LocalWaker` into a `Waker`.
-    ///
-    /// `Waker` is nearly identical to `LocalWaker`, but is threadsafe
-    /// (implements `Send` and `Sync`).
-    #[inline]
-    pub fn into_waker(self) -> Waker {
-        self.0
-    }
-
-    /// Wake up the task associated with this `LocalWaker`.
-    #[inline]
-    pub fn wake(&self) {
-        unsafe { self.0.inner.as_ref().wake_local() }
-    }
-
-    /// Returns whether or not this `LocalWaker` and `other` `LocalWaker` awaken the same task.
-    ///
-    /// This function works on a best-effort basis, and may return false even
-    /// when the `LocalWaker`s would awaken the same task. However, if this function
-    /// returns true, it is guaranteed that the `LocalWaker`s will awaken the same
-    /// task.
-    ///
-    /// This function is primarily used for optimization purposes.
-    #[inline]
-    pub fn will_wake(&self, other: &LocalWaker) -> bool {
-        self.0.will_wake(&other.0)
-    }
-
-    /// Returns whether or not this `LocalWaker` and `other` `Waker` awaken the same task.
-    ///
-    /// This function works on a best-effort basis, and may return false even
-    /// when the `Waker`s would awaken the same task. However, if this function
-    /// returns true, it is guaranteed that the `LocalWaker`s will awaken the same
-    /// task.
-    ///
-    /// This function is primarily used for optimization purposes.
-    #[inline]
-    pub fn will_wake_nonlocal(&self, other: &Waker) -> bool {
-        self.0.will_wake(other)
-    }
-}
-
-impl From<LocalWaker> for Waker {
-    /// Converts a `LocalWaker` into a `Waker`.
-    ///
-    /// This conversion turns a `!Sync` `LocalWaker` into a `Sync` `Waker`, allowing a wakeup
-    /// object to be sent to another thread, but giving up its ability to do specialized
-    /// thread-local wakeup behavior.
-    #[inline]
-    fn from(local_waker: LocalWaker) -> Self {
-        local_waker.0
-    }
-}
-
-impl fmt::Debug for LocalWaker {
+impl fmt::Debug for Waker {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        f.debug_struct("LocalWaker")
+        f.debug_struct("Waker")
             .finish()
     }
 }
-
-/// An unsafe trait for implementing custom memory management for a `Waker` or `LocalWaker`.
-///
-/// A `Waker` conceptually is a cloneable trait object for `Wake`, and is
-/// most often essentially just `Arc<dyn Wake>`. However, in some contexts
-/// (particularly `no_std`), it's desirable to avoid `Arc` in favor of some
-/// custom memory management strategy. This trait is designed to allow for such
-/// customization.
-///
-/// When using `std`, a default implementation of the `UnsafeWake` trait is provided for
-/// `Arc<T>` where `T: Wake`.
-pub unsafe trait UnsafeWake: Send + Sync {
-    /// Creates a clone of this `UnsafeWake` and stores it behind a `Waker`.
-    ///
-    /// This function will create a new uniquely owned handle that under the
-    /// hood references the same notification instance. In other words calls
-    /// to `wake` on the returned handle should be equivalent to calls to
-    /// `wake` on this handle.
-    ///
-    /// # Unsafety
-    ///
-    /// This function is unsafe to call because it's asserting the `UnsafeWake`
-    /// value is in a consistent state, i.e., hasn't been dropped.
-    unsafe fn clone_raw(&self) -> Waker;
-
-    /// Drops this instance of `UnsafeWake`, deallocating resources
-    /// associated with it.
-    ///
-    /// FIXME(cramertj)
-    /// This method is intended to have a signature such as:
-    ///
-    /// ```ignore (not-a-doctest)
-    /// fn drop_raw(self: *mut Self);
-    /// ```
-    ///
-    /// Unfortunately in Rust today that signature is not object safe.
-    /// Nevertheless it's recommended to implement this function *as if* that
-    /// were its signature. As such it is not safe to call on an invalid
-    /// pointer, nor is the validity of the pointer guaranteed after this
-    /// function returns.
-    ///
-    /// # Unsafety
-    ///
-    /// This function is unsafe to call because it's asserting the `UnsafeWake`
-    /// value is in a consistent state, i.e., hasn't been dropped.
-    unsafe fn drop_raw(&self);
-
-    /// Indicates that the associated task is ready to make progress and should
-    /// be `poll`ed.
-    ///
-    /// Executors generally maintain a queue of "ready" tasks; `wake` should place
-    /// the associated task onto this queue.
-    ///
-    /// # Panics
-    ///
-    /// Implementations should avoid panicking, but clients should also be prepared
-    /// for panics.
-    ///
-    /// # Unsafety
-    ///
-    /// This function is unsafe to call because it's asserting the `UnsafeWake`
-    /// value is in a consistent state, i.e., hasn't been dropped.
-    unsafe fn wake(&self);
-
-    /// Indicates that the associated task is ready to make progress and should
-    /// be `poll`ed. This function is the same as `wake`, but can only be called
-    /// from the thread that this `UnsafeWake` is "local" to. This allows for
-    /// implementors to provide specialized wakeup behavior specific to the current
-    /// thread. This function is called by `LocalWaker::wake`.
-    ///
-    /// Executors generally maintain a queue of "ready" tasks; `wake_local` should place
-    /// the associated task onto this queue.
-    ///
-    /// # Panics
-    ///
-    /// Implementations should avoid panicking, but clients should also be prepared
-    /// for panics.
-    ///
-    /// # Unsafety
-    ///
-    /// This function is unsafe to call because it's asserting the `UnsafeWake`
-    /// value is in a consistent state, i.e., hasn't been dropped, and that the
-    /// `UnsafeWake` hasn't moved from the thread on which it was created.
-    unsafe fn wake_local(&self) {
-        self.wake()
-    }
-}