pub struct UnboundedReceiver<T> { /* private fields */ }展开描述
从关联的 UnboundedSender 接收值。
实例
由
unbounded_channel
函数创建。
此 receiver
可以使用
UnboundedReceiverStream
转换为
Stream。
实现§
Source§impl<T> UnboundedReceiver<T>
impl<T> UnboundedReceiver<T>
Sourcepub async fn recv(&mut self) -> Option<T>
pub async fn recv(&mut self) -> Option<T>
接收此接收者的下一个值。
如果通道已关闭且通道的缓冲区中没有剩余消息,此方法返回 None。这表示再也无法从此 Receiver 接收到任何值。当所有发送者都已被丢弃或调用了 close 时,通道被关闭。
如果通道的缓冲区中没有消息,但通道尚未关闭,此方法将休眠直到发送消息或通道被关闭。
§Cancel safety
此方法是取消安全的。如果 recv 在 tokio::select! 语句中作为事件使用,并且其他分支首先完成,则可以保证此通道上没有接收到消息。
§示例
use tokio::sync::mpsc;
let (tx, mut rx) = mpsc::unbounded_channel();
tokio::spawn(async move {
tx.send("hello").unwrap();
});
assert_eq!(Some("hello"), rx.recv().await);
assert_eq!(None, rx.recv().await);值已缓冲:
use tokio::sync::mpsc;
let (tx, mut rx) = mpsc::unbounded_channel();
tx.send("hello").unwrap();
tx.send("world").unwrap();
assert_eq!(Some("hello"), rx.recv().await);
assert_eq!(Some("world"), rx.recv().await);Sourcepub async fn recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize
pub async fn recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize
接收此接收者的下一些值并扩展缓冲区。
此方法最多将缓冲区扩展 limit 指定数量的值。如果 limit 为零,函数立即返回 0。返回值是已添加到缓冲区的值数量。
对于 limit > 0,如果通道的队列中没有消息,但通道尚未关闭,此方法将休眠直到发送消息或通道被关闭。
对于非零的 limit 值,此方法永远不会返回 0,除非通道已关闭且通道的队列中没有剩余消息。这表示再也无法从此 Receiver 接收到任何值。当所有发送者都已被丢弃或调用了 close 时,通道被关闭。
buffer 的容量按需增加。
§Cancel safety
此方法是取消安全的。如果 recv_many 在 tokio::select! 语句中作为事件使用,并且其他分支首先完成,则可以保证此通道上没有接收到消息。
§示例
use tokio::sync::mpsc;
let mut buffer: Vec<&str> = Vec::with_capacity(2);
let limit = 2;
let (tx, mut rx) = mpsc::unbounded_channel();
let tx2 = tx.clone();
tx2.send("first").unwrap();
tx2.send("second").unwrap();
tx2.send("third").unwrap();
// Call `recv_many` to receive up to `limit` (2) values.
assert_eq!(2, rx.recv_many(&mut buffer, limit).await);
assert_eq!(vec!["first", "second"], buffer);
// If the buffer is full, the next call to `recv_many`
// reserves additional capacity.
assert_eq!(1, rx.recv_many(&mut buffer, limit).await);
tokio::spawn(async move {
tx.send("fourth").unwrap();
});
// 'tx' is dropped, but `recv_many`
// is guaranteed not to return 0 as the channel
// is not yet closed.
assert_eq!(1, rx.recv_many(&mut buffer, limit).await);
assert_eq!(vec!["first", "second", "third", "fourth"], buffer);
// Once the last sender is dropped, the channel is
// closed and `recv_many` returns 0, capacity unchanged.
drop(tx2);
assert_eq!(0, rx.recv_many(&mut buffer, limit).await);
assert_eq!(vec!["first", "second", "third", "fourth"], buffer);Sourcepub fn try_recv(&mut self) -> Result<T, TryRecvError>
pub fn try_recv(&mut self) -> Result<T, TryRecvError>
尝试接收此接收者的下一个值。
如果通道当前为空但仍有未完成的 sender 或 permit,此方法返回 Empty 错误。
如果通道当前为空且没有未完成的 sender 或 permit,此方法返回 Disconnected 错误。
与 poll_recv 方法不同,此方法绝不会虚假地返回 Empty 错误。
§示例
use tokio::sync::mpsc;
use tokio::sync::mpsc::error::TryRecvError;
let (tx, mut rx) = mpsc::unbounded_channel();
tx.send("hello").unwrap();
assert_eq!(Ok("hello"), rx.try_recv());
assert_eq!(Err(TryRecvError::Empty), rx.try_recv());
tx.send("hello").unwrap();
// Drop the last sender, closing the channel.
drop(tx);
assert_eq!(Ok("hello"), rx.try_recv());
assert_eq!(Err(TryRecvError::Disconnected), rx.try_recv());Sourcepub fn blocking_recv(&mut self) -> Option<T>
pub fn blocking_recv(&mut self) -> Option<T>
在异步上下文之外调用的阻塞接收。
§Panics
如果在异步执行上下文中调用此函数会触发 panic。
§示例
use std::thread;
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::unbounded_channel::<u8>();
let sync_code = thread::spawn(move || {
assert_eq!(Some(10), rx.blocking_recv());
});
let _ = tx.send(10);
sync_code.join().unwrap();
}Sourcepub fn blocking_recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize
pub fn blocking_recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize
用于阻塞上下文的 Self::recv_many 变体。
适用与 Self::blocking_recv 相同的条件。
Sourcepub fn close(&mut self)
pub fn close(&mut self)
关闭通道的接收半部,而不丢弃它。
这会阻止通过此通道发送更多消息,同时仍允许接收者排空已缓冲的消息。
为了保证不丢失消息,调用 close() 后必须反复调用 recv() 直到返回 None。
Sourcepub fn is_closed(&self) -> bool
pub fn is_closed(&self) -> bool
检查通道是否已关闭。
如果通道已关闭,此方法返回 true。当所有 UnboundedSender 都已被丢弃或调用了 UnboundedReceiver::close 时,通道被关闭。
§示例
use tokio::sync::mpsc;
let (_tx, mut rx) = mpsc::unbounded_channel::<()>();
assert!(!rx.is_closed());
rx.close();
assert!(rx.is_closed());Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
检查通道是否为空。
如果通道没有消息,此方法返回 true。
§示例
use tokio::sync::mpsc;
let (tx, rx) = mpsc::unbounded_channel();
assert!(rx.is_empty());
tx.send(0).unwrap();
assert!(!rx.is_empty());
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
返回通道中的消息数量。
§示例
use tokio::sync::mpsc;
let (tx, rx) = mpsc::unbounded_channel();
assert_eq!(0, rx.len());
tx.send(0).unwrap();
assert_eq!(1, rx.len());Sourcepub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>>
pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>>
poll 以接收此通道上的下一条消息。
此方法返回:
Poll::Pendingif no messages are available but the channel is not closed, or if a spurious failure happens.Poll::Ready(Some(message))if a message is available.Poll::Ready(None)if the channel has been closed and all messages sent before it was closed have been received.
当方法返回 Poll::Pending 时,提供的 Context 中的 Waker 被调度为在任一接收者上发送消息时或通道关闭时接收唤醒。请注意,对 poll_recv 或 poll_recv_many 的多次调用,只有最近一次调用传递的 Context 中的 Waker 会被调度为接收唤醒。
如果此方法因虚假失败而返回 Poll::Pending,则当导致虚假失败的情况得到解决时,Waker 将被通知。请注意,收到这样的唤醒并不保证下一次调用会成功 —— 它可能会以另一个虚假失败而失败。
Sourcepub fn poll_recv_many(
&mut self,
cx: &mut Context<'_>,
buffer: &mut Vec<T>,
limit: usize,
) -> Poll<usize>
pub fn poll_recv_many( &mut self, cx: &mut Context<'_>, buffer: &mut Vec<T>, limit: usize, ) -> Poll<usize>
poll 以接收此通道上的多条消息,并扩展提供的缓冲区。
此方法返回:
Poll::Pendingif no messages are available but the channel is not closed, or if a spurious failure happens.Poll::Ready(count)wherecountis the number of messages successfully received and stored inbuffer. This can be less than, or equal to,limit.Poll::Ready(0)iflimitis set to zero or when the channel is closed.
当方法返回 Poll::Pending 时,提供的 Context 中的 Waker 被调度为在任一接收者上发送消息时或通道关闭时接收唤醒。请注意,对 poll_recv 或 poll_recv_many 的多次调用,只有最近一次调用传递的 Context 中的 Waker 会被调度为接收唤醒。
请注意,此方法不保证恰好接收 limit 条消息。而是如果至少有一条消息可用,它会尽可能返回多达 limit 条消息。仅当通道已关闭(或 limit 为零)时,此方法才返回零。
§示例
use std::task::{Context, Poll};
use std::pin::Pin;
use tokio::sync::mpsc;
use futures::Future;
struct MyReceiverFuture<'a> {
receiver: mpsc::UnboundedReceiver<i32>,
buffer: &'a mut Vec<i32>,
limit: usize,
}
impl<'a> Future for MyReceiverFuture<'a> {
type Output = usize; // Number of messages received
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let MyReceiverFuture { receiver, buffer, limit } = &mut *self;
// Now `receiver` and `buffer` are mutable references, and `limit` is copied
match receiver.poll_recv_many(cx, *buffer, *limit) {
Poll::Pending => Poll::Pending,
Poll::Ready(count) => Poll::Ready(count),
}
}
}
let (tx, rx) = mpsc::unbounded_channel::<i32>();
let mut buffer = Vec::new();
let my_receiver_future = MyReceiverFuture {
receiver: rx,
buffer: &mut buffer,
limit: 3,
};
for i in 0..10 {
tx.send(i).expect("Unable to send integer");
}
let count = my_receiver_future.await;
assert_eq!(count, 3);
assert_eq!(buffer, vec![0,1,2])Sourcepub fn sender_strong_count(&self) -> usize
pub fn sender_strong_count(&self) -> usize
返回 UnboundedSender 句柄的数量。
Sourcepub fn sender_weak_count(&self) -> usize
pub fn sender_weak_count(&self) -> usize
返回 WeakUnboundedSender 句柄的数量。