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