pub struct Notified<'a> { /* private fields */ }
Expand description

Future returned from Notify::notified().

This future is fused, so once it has completed, any future calls to poll will immediately return Poll::Ready.

Implementations§

source§

impl Notified<'_>

source

pub fn enable(self: Pin<&mut Notified<'_>>) -> bool

Adds this future to the list of futures that are ready to receive wakeups from calls to notify_one.

Polling the future also adds it to the list, so this method should only be used if you want to add the future to the list before the first call to poll. (In fact, this method is equivalent to calling poll except that no Waker is registered.)

This has no effect on notifications sent using notify_waiters, which are received as long as they happen after the creation of the Notified regardless of whether enable or poll has been called.

This method returns true if the Notified is ready. This happens in the following situations:

  1. The notify_waiters method was called between the creation of the Notified and the call to this method.
  2. This is the first call to enable or poll on this future, and the Notify was holding a permit from a previous call to notify_one. The call consumes the permit in that case.
  3. The future has previously been enabled or polled, and it has since then been marked ready by either consuming a permit from the Notify, or by a call to notify_one or notify_waiters that removed it from the list of futures ready to receive wakeups.

If this method returns true, any future calls to poll on the same future will immediately return Poll::Ready.

Examples

Unbound multi-producer multi-consumer (mpmc) channel.

The call to enable is important because otherwise if you have two calls to recv and two calls to send in parallel, the following could happen:

  1. Both calls to try_recv return None.
  2. Both new elements are added to the vector.
  3. The notify_one method is called twice, adding only a single permit to the Notify.
  4. Both calls to recv reach the Notified future. One of them consumes the permit, and the other sleeps forever.

By adding the Notified futures to the list by calling enable before try_recv, the notify_one calls in step three would remove the futures from the list and mark them notified instead of adding a permit to the Notify. This ensures that both futures are woken.

use tokio::sync::Notify;

use std::collections::VecDeque;
use std::sync::Mutex;

struct Channel<T> {
    messages: Mutex<VecDeque<T>>,
    notify_on_sent: Notify,
}

impl<T> Channel<T> {
    pub fn send(&self, msg: T) {
        let mut locked_queue = self.messages.lock().unwrap();
        locked_queue.push_back(msg);
        drop(locked_queue);

        // Send a notification to one of the calls currently
        // waiting in a call to `recv`.
        self.notify_on_sent.notify_one();
    }

    pub fn try_recv(&self) -> Option<T> {
        let mut locked_queue = self.messages.lock().unwrap();
        locked_queue.pop_front()
    }

    pub async fn recv(&self) -> T {
        let future = self.notify_on_sent.notified();
        tokio::pin!(future);

        loop {
            // Make sure that no wakeup is lost if we get
            // `None` from `try_recv`.
            future.as_mut().enable();

            if let Some(msg) = self.try_recv() {
                return msg;
            }

            // Wait for a call to `notify_one`.
            //
            // This uses `.as_mut()` to avoid consuming the future,
            // which lets us call `Pin::set` below.
            future.as_mut().await;

            // Reset the future in case another call to
            // `try_recv` got the message before us.
            future.set(self.notify_on_sent.notified());
        }
    }
}

Trait Implementations§

source§

impl<'a> Debug for Notified<'a>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Drop for Notified<'_>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl Future for Notified<'_>

§

type Output = ()

The type of value produced on completion.
source§

fn poll(self: Pin<&mut Notified<'_>>, cx: &mut Context<'_>) -> Poll<()>

Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more
source§

impl<'a> Send for Notified<'a>

source§

impl<'a> Sync for Notified<'a>

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Notified<'a>

§

impl<'a> !Unpin for Notified<'a>

§

impl<'a> !UnwindSafe for Notified<'a>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Any for Twhere T: Any,

§

fn into_any(self: Box<T, Global>) -> Box<dyn Any, Global>

§

fn into_any_rc(self: Rc<T, Global>) -> Rc<dyn Any, Global>

§

fn type_name(&self) -> &'static str

§

impl<T> AnySync for Twhere T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T, Global>) -> Arc<dyn Any + Sync + Send, Global>

§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

§

fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for Twhere T: Future + ?Sized,

§

fn map<U, F>(self, f: F) -> Map<Self, F> where F: FnOnce(Self::Output) -> U, Self: Sized,

Map this future’s output to a different type, returning a new future of the resulting type. Read more
§

fn map_into<U>(self) -> MapInto<Self, U> where Self::Output: Into<U>, Self: Sized,

Map this future’s output to a different type, returning a new future of the resulting type. Read more
§

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F> where F: FnOnce(Self::Output) -> Fut, Fut: Future, Self: Sized,

Chain on a computation for when a future finished, passing the result of the future to the provided closure f. Read more
§

fn left_future<B>(self) -> Either<Self, B> where B: Future<Output = Self::Output>, Self: Sized,

Wrap this future in an Either future, making it the left-hand variant of that Either. Read more
§

fn right_future<A>(self) -> Either<A, Self> where A: Future<Output = Self::Output>, Self: Sized,

Wrap this future in an Either future, making it the right-hand variant of that Either. Read more
§

fn into_stream(self) -> IntoStream<Self>where Self: Sized,

Convert this future into a single element stream. Read more
§

fn flatten(self) -> Flatten<Self> where Self::Output: Future, Self: Sized,

Flatten the execution of this future when the output of this future is itself another future. Read more
§

fn flatten_stream(self) -> FlattenStream<Self>where Self::Output: Stream, Self: Sized,

Flatten the execution of this future when the successful result of this future is a stream. Read more
§

fn fuse(self) -> Fuse<Self> where Self: Sized,

Fuse a future such that poll will never again be called once it has completed. This method can be used to turn any Future into a FusedFuture. Read more
§

fn inspect<F>(self, f: F) -> Inspect<Self, F> where F: FnOnce(&Self::Output), Self: Sized,

Do something with the output of a future before passing it on. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self> where Self: Sized + UnwindSafe,

Catches unwinding panics while polling the future. Read more
§

fn shared(self) -> Shared<Self> where Self: Sized, Self::Output: Clone,

Create a cloneable handle to this future where all handles will resolve to the same result. Read more
§

fn remote_handle(self) -> (Remote<Self>, RemoteHandle<Self::Output>)where Self: Sized,

Turn this future into a future that yields () on completion and sends its output to another future on a separate task. Read more
§

fn boxed<'a>( self ) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a, Global>>where Self: Sized + Send + 'a,

Wrap the future in a Box, pinning it. Read more
§

fn boxed_local<'a>( self ) -> Pin<Box<dyn Future<Output = Self::Output> + 'a, Global>>where Self: Sized + 'a,

Wrap the future in a Box, pinning it. Read more
§

fn unit_error(self) -> UnitError<Self> where Self: Sized,

§

fn never_error(self) -> NeverError<Self> where Self: Sized,

§

fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>where Self: Unpin,

A convenience for calling Future::poll on Unpin future types.
§

fn now_or_never(self) -> Option<Self::Output>where Self: Sized,

Evaluates and consumes the future, returning the resulting output if the future is ready after the first call to Future::poll. Read more
§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> FutureExt for Twhere T: Future + ?Sized,

§

fn delay(self, dur: Duration) -> DelayFuture<Self>where Self: Sized,

Returns a Future that delays execution for a specified time. Read more
§

fn flatten(self) -> FlattenFuture<Self, <Self::Output as IntoFuture>::Future>where Self: Sized, Self::Output: IntoFuture,

Flatten out the execution of this future when the result itself can be converted into another future. Read more
§

fn race<F>(self, other: F) -> Race<Self, F>where Self: Future + Sized, F: Future<Output = Self::Output>,

Waits for one of two similarly-typed futures to complete. Read more
§

fn try_race<F, T, E>(self, other: F) -> TryRace<Self, F>where Self: Future<Output = Result<T, E>> + Sized, F: Future<Output = Self::Output>,

Waits for one of two similarly-typed fallible futures to complete. Read more
§

fn join<F>(self, other: F) -> Join<Self, F>where Self: Future + Sized, F: Future,

Waits for two similarly-typed futures to complete. Read more
§

fn try_join<F, A, B, E>(self, other: F) -> TryJoin<Self, F>where Self: Future<Output = Result<A, E>> + Sized, F: Future<Output = Result<B, E>>,

Waits for two similarly-typed fallible futures to complete. Read more
§

fn timeout(self, dur: Duration) -> TimeoutFuture<Self>where Self: Sized,

Waits for both the future and a timeout, if the timeout completes before the future, it returns a TimeoutError. Read more
§

impl<F> FutureExt for Fwhere F: Future + ?Sized,

§

fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>where Self: Unpin,

A convenience for calling Future::poll() on !Unpin types.
§

fn or<F>(self, other: F) -> Or<Self, F> where Self: Sized, F: Future<Output = Self::Output>,

Returns the result of self or other future, preferring self if both are ready. Read more
§

fn race<F>(self, other: F) -> Race<Self, F> where Self: Sized, F: Future<Output = Self::Output>,

Returns the result of self or other future, with no preference if both are ready. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self> where Self: Sized + UnwindSafe,

Catches panics while polling the future. Read more
§

fn boxed<'a>( self ) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a, Global>>where Self: Sized + Send + 'a,

Boxes the future and changes its type to dyn Future + Send + 'a. Read more
§

fn boxed_local<'a>( self ) -> Pin<Box<dyn Future<Output = Self::Output> + 'a, Global>>where Self: Sized + 'a,

Boxes the future and changes its type to dyn Future + 'a. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<F> IntoFuture for Fwhere F: Future,

§

type Output = <F as Future>::Output

The output that the future will produce on completion.
§

type IntoFuture = F

Which kind of future are we turning this into?
source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
§

impl<T> IntoFuture for Twhere T: Future,

§

type Output = <T as Future>::Output

The type of value produced on completion.
§

type Future = T

Which kind of future are we turning this into?
§

fn into_future(self) -> <T as IntoFuture>::Future

Create a future from a value
source§

impl<T> IntoMustBoxFuture for Twhere T: Future + ?Sized,

source§

fn must_box<'a>(self) -> MustBoxFuture<'a, Self::Output> where Self: 'a + Sized + Send,

Convert this raw future into a MustBoxFuture
§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Metadata = ()

The type for metadata in pointers and references to Self.
source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SPwhere SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcastable for Twhere T: Any + Send + Sync + 'static,

§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

upcast ref
§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

upcast mut ref
§

fn upcast_any_box(self: Box<T, Global>) -> Box<dyn Any, Global>

upcast boxed dyn
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more