tokio/sync/mpsc/mod.rs
1#![cfg_attr(not(feature = "sync"), allow(dead_code, unreachable_pub))]
2
3//! A multi-producer, single-consumer queue for sending values between
4//! asynchronous tasks.
5//!
6//! This module provides two variants of the channel: bounded and unbounded. The
7//! bounded variant has a limit on the number of messages that the channel can
8//! store, and if this limit is reached, trying to send another message will
9//! wait until a message is received from the channel. An unbounded channel has
10//! an infinite capacity, so the `send` method will always complete immediately.
11//! This makes the [`UnboundedSender`] usable from both synchronous and
12//! asynchronous code.
13//!
14//! Similar to the `mpsc` channels provided by `std`, the channel constructor
15//! functions provide separate send and receive handles, [`Sender`] and
16//! [`Receiver`] for the bounded channel, [`UnboundedSender`] and
17//! [`UnboundedReceiver`] for the unbounded channel. If there is no message to read,
18//! the current task will be notified when a new value is sent. [`Sender`] and
19//! [`UnboundedSender`] allow sending values into the channel. If the bounded
20//! channel is at capacity, the send is rejected and the task will be notified
21//! when additional capacity is available. In other words, the channel provides
22//! backpressure.
23//!
24//! This channel is also suitable for the single-producer single-consumer
25//! use-case. (Unless you only need to send one message, in which case you
26//! should use the [oneshot] channel.)
27//!
28//! # Disconnection
29//!
30//! When all [`Sender`] handles have been dropped, it is no longer
31//! possible to send values into the channel. This is considered the termination
32//! event of the stream. Once all senders have been dropped and any remaining
33//! buffered values have been received, `Receiver::recv` returns `None`
34//! (and `Receiver::poll_recv` returns `Poll::Ready(None)`).
35//!
36//! If the [`Receiver`] handle is dropped, then messages can no longer
37//! be read out of the channel. In this case, all further attempts to send will
38//! result in an error. Additionally, all unread messages will be drained from the
39//! channel and dropped.
40//!
41//! # Clean Shutdown
42//!
43//! When the [`Receiver`] is dropped, it is possible for unprocessed messages to
44//! remain in the channel. Instead, it is usually desirable to perform a "clean"
45//! shutdown. To do this, the receiver first calls `close`, which will prevent
46//! any further messages to be sent into the channel. Then, the receiver
47//! consumes the channel to completion, at which point the receiver can be
48//! dropped.
49//!
50//! # Communicating between sync and async code
51//!
52//! When you want to communicate between synchronous and asynchronous code, there
53//! are two situations to consider:
54//!
55//! **Bounded channel**: If you need a bounded channel, you should use a bounded
56//! Tokio `mpsc` channel for both directions of communication. Instead of calling
57//! the async [`send`][bounded-send] or [`recv`][bounded-recv] methods, in
58//! synchronous code you will need to use the [`blocking_send`][blocking-send] or
59//! [`blocking_recv`][blocking-recv] methods.
60//!
61//! **Unbounded channel**: You should use the kind of channel that matches where
62//! the receiver is. So for sending a message _from async to sync_, you should
63//! use [the standard library unbounded channel][std-unbounded] or
64//! [crossbeam][crossbeam-unbounded]. Similarly, for sending a message _from sync
65//! to async_, you should use an unbounded Tokio `mpsc` channel.
66//!
67//! Please be aware that the above remarks were written with the `mpsc` channel
68//! in mind, but they can also be generalized to other kinds of channels. In
69//! general, any channel method that isn't marked async can be called anywhere,
70//! including outside of the runtime. For example, sending a message on a
71//! [oneshot] channel from outside the runtime is perfectly fine.
72//!
73//! # Multiple runtimes
74//!
75//! The `mpsc` channel is runtime agnostic. You can freely move it between
76//! different instances of the Tokio runtime or even use it from non-Tokio
77//! runtimes.
78//!
79//! When used in a Tokio runtime, it participates in
80//! [cooperative scheduling](crate::task::coop#cooperative-scheduling) to avoid
81//! starvation. This feature does not apply when used from non-Tokio runtimes.
82//!
83//! As an exception, methods ending in `_timeout` are not runtime agnostic
84//! because they require access to the Tokio timer. See the documentation of
85//! each `*_timeout` method for more information on its use.
86//!
87//! # Allocation behavior
88//!
89//! <div class="warning">The implementation details described in this section may change in future
90//! Tokio releases.</div>
91//!
92//! The mpsc channel stores elements in blocks. Blocks are organized in a linked list. Sending
93//! pushes new elements onto the block at the front of the list, and receiving pops them off the
94//! one at the back. A block can hold 32 messages on a 64-bit target and 16 messages on a 32-bit
95//! target. This number is independent of channel and message size. Each block also stores 4
96//! pointer-sized values for bookkeeping (so on a 64-bit machine, each message has 1 byte of
97//! overhead).
98//!
99//! When all values in a block have been received, it becomes empty. It will then be freed, unless
100//! the channel's first block (where newly-sent elements are being stored) has no next block. In
101//! that case, the empty block is reused as the next block.
102//!
103//! [`Sender`]: crate::sync::mpsc::Sender
104//! [`Receiver`]: crate::sync::mpsc::Receiver
105//! [bounded-send]: crate::sync::mpsc::Sender::send()
106//! [bounded-recv]: crate::sync::mpsc::Receiver::recv()
107//! [blocking-send]: crate::sync::mpsc::Sender::blocking_send()
108//! [blocking-recv]: crate::sync::mpsc::Receiver::blocking_recv()
109//! [`UnboundedSender`]: crate::sync::mpsc::UnboundedSender
110//! [`UnboundedReceiver`]: crate::sync::mpsc::UnboundedReceiver
111//! [oneshot]: crate::sync::oneshot
112//! [`Handle::block_on`]: crate::runtime::Handle::block_on()
113//! [std-unbounded]: std::sync::mpsc::channel
114//! [crossbeam-unbounded]: https://docs.rs/crossbeam/*/crossbeam/channel/fn.unbounded.html
115//! [`send_timeout`]: crate::sync::mpsc::Sender::send_timeout
116
117pub(super) mod block;
118
119mod bounded;
120pub use self::bounded::{
121 channel, OwnedPermit, Permit, PermitIterator, Receiver, Sender, WeakSender,
122};
123
124mod chan;
125
126pub(super) mod list;
127
128mod unbounded;
129pub use self::unbounded::{
130 unbounded_channel, UnboundedReceiver, UnboundedSender, WeakUnboundedSender,
131};
132
133pub mod error;
134
135/// The number of values a block can contain.
136///
137/// This value must be a power of 2. It also must be smaller than the number of
138/// bits in `usize`.
139#[cfg(all(target_pointer_width = "64", not(loom)))]
140const BLOCK_CAP: usize = 32;
141
142#[cfg(all(not(target_pointer_width = "64"), not(loom)))]
143const BLOCK_CAP: usize = 16;
144
145#[cfg(loom)]
146const BLOCK_CAP: usize = 2;