pub struct UnboundedSender<T> { /* 私有字段 */ }展开描述
向关联的 UnboundedReceiver 发送值。
实例由 unbounded_channel 函数创建。
实现§
源代码§impl<T> UnboundedSender<T>
impl<T> UnboundedSender<T>
源代码pub fn send(&self, message: T) -> Result<(), SendError<T>>
pub fn send(&self, message: T) -> Result<(), SendError<T>>
尝试在不阻塞的情况下通过此 UnboundedSender 发送消息。
此方法未标记为 async,因为向无界 channel 发送消息永远不需要任何形式的等待。这是由于 channel 的无限容量,允许 send 操作立即完成。因此,send 方法可以在同步和异步代码中使用而不会出现问题。
如果 channel 的接收端已关闭(无论是由于调用了 close 还是 UnboundedReceiver 已被 drop),则此函数返回错误。错误包括传递给 send 的值。
源代码pub async fn closed(&self)
pub async fn closed(&self)
当 receiver 被 drop 时完成。
这允许生产者在对所产生值的兴趣被取消时收到通知,并立即停止工作。
§取消安全性
此方法可安全取消。一旦通道关闭,它将永远保持关闭状态,并且所有对 closed 的未来调用都将立即返回。
§示例
use tokio::sync::mpsc;
let (tx1, rx) = mpsc::unbounded_channel::<()>();
let tx2 = tx1.clone();
let tx3 = tx1.clone();
let tx4 = tx1.clone();
let tx5 = tx1.clone();
tokio::spawn(async move {
drop(rx);
});
futures::join!(
tx1.closed(),
tx2.closed(),
tx3.closed(),
tx4.closed(),
tx5.closed()
);
println!("Receiver dropped");源代码pub fn is_closed(&self) -> bool
pub fn is_closed(&self) -> bool
检查 channel 是否已关闭。当 UnboundedReceiver 被 drop,或调用 UnboundedReceiver::close 方法时,会发生这种情况。
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<()>();
assert!(!tx.is_closed());
let tx2 = tx.clone();
assert!(!tx2.is_closed());
drop(rx);
assert!(tx.is_closed());
assert!(tx2.is_closed());源代码pub fn same_channel(&self, other: &Self) -> bool
pub fn same_channel(&self, other: &Self) -> bool
如果这些 sender 属于同一个通道,则返回 true。
§示例
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<()>();
let tx2 = tx.clone();
assert!(tx.same_channel(&tx2));
let (tx3, rx3) = tokio::sync::mpsc::unbounded_channel::<()>();
assert!(!tx3.same_channel(&tx2));源代码pub fn downgrade(&self) -> WeakUnboundedSender<T>
pub fn downgrade(&self) -> WeakUnboundedSender<T>
将 UnboundedSender 转换为 WeakUnboundedSender,后者不计入 RAII 语义,即如果 channel 的所有 UnboundedSender 实例都已被 drop,仅剩下 WeakUnboundedSender 实例,则 channel 关闭。
源代码pub fn strong_count(&self) -> usize
pub fn strong_count(&self) -> usize
返回 UnboundedSender 句柄的数量。
源代码pub fn weak_count(&self) -> usize
pub fn weak_count(&self) -> usize
返回 WeakUnboundedSender 句柄的数量。
trait 实现§
源代码§impl<T> Clone for UnboundedSender<T>
impl<T> Clone for UnboundedSender<T>
自动 trait 实现§
impl<T> Freeze for UnboundedSender<T>
impl<T> RefUnwindSafe for UnboundedSender<T>
impl<T> Send for UnboundedSender<T>where
T: Send,
impl<T> Sync for UnboundedSender<T>where
T: Send,
impl<T> Unpin for UnboundedSender<T>
impl<T> UnsafeUnpin for UnboundedSender<T>
impl<T> UnwindSafe for UnboundedSender<T>
blanket 实现§
源代码§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
源代码§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. 更多信息