Struct Sender
struct Sender<T> { ... }
Sends values to the associated Receiver.
Instances are created by the channel function.
To convert the Sender into a Sink or use it in a poll function, you can
use the PollSender utility.
Implementations
impl<T> Sender<T>
async fn send(self: &Self, value: T) -> Result<(), SendError<T>>Sends a value, waiting until there is capacity.
A successful send occurs when it is determined that the other end of the channel has not hung up already. An unsuccessful send would be one where the corresponding receiver has already been closed. Note that a return value of
Errmeans that the data will never be received, but a return value ofOkdoes not mean that the data will be received. It is possible for the corresponding receiver to hang up immediately after this function returnsOk.Errors
If the receive half of the channel is closed, either due to
closebeing called or theReceiverhandle dropping, the function returns an error. The error includes the value passed tosend.Cancel safety
If
sendis used as the event in atokio::select!statement and some other branch completes first, then it is guaranteed that the message was not sent. However, in that case, the message is dropped and will be lost.To avoid losing messages, use
reserveto reserve capacity, then use the returnedPermitto send the message.This channel uses a queue to ensure that calls to
sendandreservecomplete in the order they were requested. Cancelling a call tosendmakes you lose your place in the queue.Examples
In the following example, each call to
sendwill block until the previously sent value was received.use mpsc; asyncasync fn closed(self: &Self)Completes when the receiver has dropped.
This allows the producers to get notified when interest in the produced values is canceled and immediately stop doing work.
Cancel safety
This method is cancel safe. Once the channel is closed, it stays closed forever and all future calls to
closedwill return immediately.Examples
use mpsc; asyncfn try_send(self: &Self, message: T) -> Result<(), TrySendError<T>>Attempts to immediately send a message on this
SenderThis method differs from
sendby returning immediately if the channel's buffer is full or no receiver is waiting to acquire some data. Compared withsend, this function has two failure cases instead of one (one for disconnection, one for a full buffer).Errors
If the channel capacity has been reached, i.e., the channel has
nbuffered values wherenis the argument passed tochannel, then an error is returned.If the receive half of the channel is closed, either due to
closebeing called or theReceiverhandle dropping, the function returns an error. The error includes the value passed tosend.Examples
use mpsc; asyncasync fn send_timeout(self: &Self, value: T, timeout: Duration) -> Result<(), SendTimeoutError<T>>Sends a value, waiting until there is capacity, but only for a limited time.
Shares the same success and error conditions as
send, adding one more condition for an unsuccessful send, which is when the provided timeout has elapsed, and there is no capacity available.Errors
If the receive half of the channel is closed, either due to
closebeing called or theReceiverhaving been dropped, the function returns an error. The error includes the value passed tosend.Panics
This function panics if it is called outside the context of a Tokio runtime with time enabled.
Examples
In the following example, each call to
send_timeoutwill block until the previously sent value was received, unless the timeout has elapsed.use mpsc; use ; asyncfn blocking_send(self: &Self, value: T) -> Result<(), SendError<T>>Blocking send to call outside of asynchronous contexts.
This method is intended for use cases where you are sending from synchronous code to asynchronous code, and will work even if the receiver is not using
blocking_recvto receive the message.Panics
This function panics if called within an asynchronous execution context.
Examples
use thread; use Runtime; use mpsc;fn is_closed(self: &Self) -> boolChecks if the channel has been closed. This happens when the
Receiveris dropped, or when theReceiver::closemethod is called.let = ; assert!; let tx2 = tx.clone; assert!; drop; assert!; assert!;async fn reserve(self: &Self) -> Result<Permit<'_, T>, SendError<()>>Waits for channel capacity. Once capacity to send one message is available, it is reserved for the caller.
If the channel is full, the function waits for the number of unreceived messages to become less than the channel capacity. Capacity to send one message is reserved for the caller. A
Permitis returned to track the reserved capacity. Thesendfunction onPermitconsumes the reserved capacity.Dropping
Permitwithout sending a message releases the capacity back to the channel.Cancel safety
This channel uses a queue to ensure that calls to
sendandreservecomplete in the order they were requested. Cancelling a call toreservemakes you lose your place in the queue.Examples
use mpsc; asyncasync fn reserve_many(self: &Self, n: usize) -> Result<PermitIterator<'_, T>, SendError<()>>Waits for channel capacity. Once capacity to send
nmessages is available, it is reserved for the caller.If the channel is full or if there are fewer than
npermits available, the function waits for the number of unreceived messages to becomenless than the channel capacity. Capacity to sendnmessage is then reserved for the caller.A
PermitIteratoris returned to track the reserved capacity. You can call thisIteratoruntil it is exhausted to get aPermitand then callPermit::send. This function is similar totry_reserve_manyexcept it awaits for the slots to become available.If the channel is closed, the function returns a
SendError.Dropping
PermitIteratorwithout consuming it entirely releases the remaining permits back to the channel.Cancel safety
This channel uses a queue to ensure that calls to
sendandreserve_manycomplete in the order they were requested. Cancelling a call toreserve_manymakes you lose your place in the queue.Examples
use mpsc; asyncasync fn reserve_owned(self: Self) -> Result<OwnedPermit<T>, SendError<()>>Waits for channel capacity, moving the
Senderand returning an owned permit. Once capacity to send one message is available, it is reserved for the caller.This moves the sender by value, and returns an owned permit that can be used to send a message into the channel. Unlike
Sender::reserve, this method may be used in cases where the permit must be valid for the'staticlifetime.Senders may be cloned cheaply (Sender::cloneis essentially a reference count increment, comparable toArc::clone), so when multipleOwnedPermits are needed or theSendercannot be moved, it can be cloned prior to callingreserve_owned.If the channel is full, the function waits for the number of unreceived messages to become less than the channel capacity. Capacity to send one message is reserved for the caller. An
OwnedPermitis returned to track the reserved capacity. Thesendfunction onOwnedPermitconsumes the reserved capacity.Dropping the
OwnedPermitwithout sending a message releases the capacity back to the channel.Cancel safety
This channel uses a queue to ensure that calls to
sendandreservecomplete in the order they were requested. Cancelling a call toreserve_ownedmakes you lose your place in the queue.Examples
Sending a message using an
OwnedPermit:use mpsc; asyncWhen multiple
OwnedPermits are needed, or the sender cannot be moved by value, it can be inexpensively cloned before callingreserve_owned:use mpsc; asyncfn try_reserve(self: &Self) -> Result<Permit<'_, T>, TrySendError<()>>Tries to acquire a slot in the channel without waiting for the slot to become available.
If the channel is full this function will return
TrySendError, otherwise if there is a slot available it will return aPermitthat will then allow you tosendon the channel with a guaranteed slot. This function is similar toreserveexcept it does not await for the slot to become available.Dropping
Permitwithout sending a message releases the capacity back to the channel.Examples
use mpsc; asyncfn try_reserve_many(self: &Self, n: usize) -> Result<PermitIterator<'_, T>, TrySendError<()>>Tries to acquire
nslots in the channel without waiting for the slot to become available.A
PermitIteratoris returned to track the reserved capacity. You can call thisIteratoruntil it is exhausted to get aPermitand then callPermit::send. This function is similar toreserve_manyexcept it does not await for the slots to become available.If there are fewer than
npermits available on the channel, then this function will return aTrySendError::Full. If the channel is closed this function will return aTrySendError::Closed.Dropping
PermitIteratorwithout consuming it entirely releases the remaining permits back to the channel.Examples
use mpsc; asyncfn try_reserve_owned(self: Self) -> Result<OwnedPermit<T>, TrySendError<Self>>Tries to acquire a slot in the channel without waiting for the slot to become available, returning an owned permit.
This moves the sender by value, and returns an owned permit that can be used to send a message into the channel. Unlike
Sender::try_reserve, this method may be used in cases where the permit must be valid for the'staticlifetime.Senders may be cloned cheaply (Sender::cloneis essentially a reference count increment, comparable toArc::clone), so when multipleOwnedPermits are needed or theSendercannot be moved, it can be cloned prior to callingtry_reserve_owned.If the channel is full this function will return a
TrySendError. Since the sender is taken by value, theTrySendErrorreturned in this case contains the sender, so that it may be used again. Otherwise, if there is a slot available, this method will return anOwnedPermitthat can then be used tosendon the channel with a guaranteed slot. This function is similar toreserve_ownedexcept it does not await for the slot to become available.Dropping the
OwnedPermitwithout sending a message releases the capacity back to the channel.Examples
use mpsc; asyncfn same_channel(self: &Self, other: &Self) -> boolReturns
trueif senders belong to the same channel.Examples
let = ; let tx2 = tx.clone; assert!; let = ; assert!;fn capacity(self: &Self) -> usizeReturns the current capacity of the channel.
The capacity goes down when sending a value by calling
sendor by reserving capacity withreserve. The capacity goes up when values are received by theReceiver. This is distinct frommax_capacity, which always returns buffer capacity initially specified when callingchannelExamples
use mpsc; asyncfn downgrade(self: &Self) -> WeakSender<T>Converts the
Senderto aWeakSenderthat does not count towards RAII semantics, i.e. if allSenderinstances of the channel were dropped and onlyWeakSenderinstances remain, the channel is closed.fn max_capacity(self: &Self) -> usizeReturns the maximum buffer capacity of the channel.
The maximum capacity is the buffer capacity initially specified when calling
channel. This is distinct fromcapacity, which returns the current available buffer capacity: as messages are sent and received, the value returned bycapacitywill go up or down, whereas the value returned bymax_capacitywill remain constant.Examples
use mpsc; asyncfn strong_count(self: &Self) -> usizeReturns the number of
Senderhandles.fn weak_count(self: &Self) -> usizeReturns the number of
WeakSenderhandles.
impl<T> Any for Sender<T>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Sender<T>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Sender<T>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> Clone for Sender<T>
fn clone(self: &Self) -> Self
impl<T> CloneToUninit for Sender<T>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> Debug for Sender<T>
fn fmt(self: &Self, fmt: &mut Formatter<'_>) -> Result
impl<T> Freeze for Sender<T>
impl<T> From for Sender<T>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> RefUnwindSafe for Sender<T>
impl<T> Send for Sender<T>
impl<T> Sync for Sender<T>
impl<T> ToOwned for Sender<T>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T> Unpin for Sender<T>
impl<T> UnsafeUnpin for Sender<T>
impl<T> UnwindSafe for Sender<T>
impl<T, U> Into for Sender<T>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Sender<T>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Sender<T>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>