跳到主要内容

Module mpsc

搜索

Module mpsc 

源代码
展开描述

用于在异步任务之间发送值的多生产者、单消费者队列。

此模块提供两种 channel 变体:有界和无界。有界变体对 channel 可以存储的消息数量有限制,如果达到此限制,则尝试发送另一条消息将等待,直到从 channel 接收一条消息为止。无界 channel 具有无限容量,因此 send 方法将始终立即完成。这使得 UnboundedSender 可用于同步和异步代码。

std 提供的 mpsc channel 类似,channel 构造函数提供单独的发送和接收句柄:有界 channel 的 SenderReceiver,无界 channel 的 UnboundedSenderUnboundedReceiver。如果没有可读取的消息,则在发送新值时将通知当前任务。SenderUnboundedSender 允许将值发送到 channel。如果有界 channel 已达到容量,则发送将被拒绝,并在有额外容量可用时通知该任务。换句话说,channel 提供了背压。

此 channel 也适用于单生产者单消费者用例。(除非你只需要发送一条消息,在这种情况下,你应该使用 oneshot channel。)

§Disconnection

当所有 Sender 句柄都已被 drop 时,就不再可能向 channel 发送值。这被视为流的终止事件。一旦所有 sender 都已被 drop 并且任何剩余的缓冲值都已接收,Receiver::recv 将返回 None(并且 Receiver::poll_recv 返回 Poll::Ready(None))。

如果 Receiver 句柄被 drop,则无法再从 channel 中读取消息。在这种情况下,所有进一步的发送尝试都将导致错误。此外,所有未读消息都将从 channel 中排出并被 drop。

§Clean Shutdown

Receiver 被 drop 时,未处理的消息可能会保留在 channel 中。相反,通常最好执行"干净"的关闭。为此,接收器首先调用 close,这将阻止任何进一步的消息发送到 channel。然后,接收器将 channel 消费到完成,此时可以 drop 接收器。

§Communicating between sync and async code

当你希望在同步和异步代码之间通信时,需要考虑两种情况:

有界 channel:如果你需要有界 channel,则应在两个通信方向上都使用有界 Tokio mpsc channel。在同步代码中,你将需要使用 blocking_sendblocking_recv 方法,而不是调用异步的 sendrecv 方法。

无界 channel:你应该使用与接收器所在位置匹配的 channel 类型。因此,要从 async 发送消息到 sync,你应该使用标准库无界 channelcrossbeam。类似地,要从 sync 发送消息到 async,你应该使用无界 Tokio mpsc channel。

请注意,以上注释是针对 mpsc channel 编写的,但它们也可以推广到其他类型的 channel。一般来说,任何未标记为 async 的 channel 方法都可以在任何地方调用,包括运行时外部。例如,在运行时外部的 oneshot channel 上发送消息是完全可以的。

§Multiple runtimes

mpsc channel 是与运行时无关的。你可以在不同的 Tokio runtime 实例之间自由移动它,甚至可以从非 Tokio runtime 中使用它。

在 Tokio runtime 中使用时,它参与协作调度以避免饥饿。从非 Tokio runtime 使用时,此功能不适用。

作为例外,以 _timeout 结尾的方法不是与运行时无关的,因为它们需要访问 Tokio 定时器。有关其使用的更多信息,请参阅各个 *_timeout 方法的文档。

§Allocation behavior

The implementation details described in this section may change in future Tokio releases.

mpsc channel 以块的形式存储元素。块以链表形式组织。发送将新元素推入链表前端的块,接收则从后端的块弹出元素。在 64 位目标上,一个块可以容纳 32 条消息;在 32 位目标上可以容纳 16 条消息。此数量与 channel 和消息大小无关。每个块还存储 4 个指针大小的值用于簿记(因此在 64 位机器上,每条消息有 1 字节的开销)。

当块中的所有值都已接收后,它变为空。然后它将被释放,除非 channel 的第一个块(正在存储新发送元素的块)没有下一个块。在这种情况下,空块将被重用作下一个块。

模块§

error
Channel error types.

结构体§

OwnedPermit
Owned permit to send one value into the channel.
Permit
Permits to send one value into the channel.
PermitIterator
An Iterator of Permit that can be used to hold n slots in the channel.
Receiver
Receives values from the associated Sender.
Sender
Sends values to the associated Receiver.
UnboundedReceiver
Receive values from the associated UnboundedSender.
UnboundedSender
Send values to the associated UnboundedReceiver.
WeakSender
A sender that does not prevent the channel from being closed.
WeakUnboundedSender
An unbounded sender that does not prevent the channel from being closed.

函数§

channel
Creates a bounded mpsc channel for communicating between asynchronous tasks with backpressure.
unbounded_channel
Creates an unbounded mpsc channel for communicating between asynchronous tasks without backpressure.