Struct std::sync::mpsc::Sender1.0.0[−][src]

pub struct Sender<T> { /* fields omitted */ }
Expand description

Rust 的异步 channel 类型的发送一半。 这一半只能由一个线程拥有,但可以克隆以发送给其他线程。

可以使用 send 通过此通道发送消息。

Note: 所有发送者 (原始和克隆) 都需要被接收者去除,以停止阻止接收带有 Receiver::recv 的消息。

Examples

use std::sync::mpsc::channel;
use std::thread;

let (sender, receiver) = channel();
let sender2 = sender.clone();

// 第一个线程拥有发送者
thread::spawn(move || {
    sender.send(1).unwrap();
});

// 第二个线程拥有 sender2
thread::spawn(move || {
    sender2.send(2).unwrap();
});

let msg = receiver.recv().unwrap();
let msg2 = receiver.recv().unwrap();

assert_eq!(3, msg + msg2);
Run

Implementations

尝试在此通道上发送值,如果无法发送,则将其返回。

当确定通道的另一端尚未挂断时,发送成功。 不成功的发送将是相应的接收者已被重新分配的发送。 请注意,返回值 Err 表示将永远不会接收到数据,但是 Ok 的返回值 不是 意味着将接收到数据。

此函数返回 Ok 之后,相应的接收者有可能立即挂断。

此方法永远不会阻塞当前线程。

Examples

use std::sync::mpsc::channel;

let (tx, rx) = channel();

// 此发送始终成功
tx.send(1).unwrap();

// 由于接收者不见了,因此发送失败
drop(rx);
assert_eq!(tx.send(1).unwrap_err().0, 1);
Run

Trait Implementations

克隆发送者以发送到其他线程。

请注意,请注意发送方的生命周期,因为所有发送方 (包括原始发送方) 都需要丢弃,以便 Receiver::recv 停止阻塞。

从 source 执行复制分配。 Read more

使用给定的格式化程序格式化该值。 Read more

执行此类型的析构函数。 Read more

Auto Trait Implementations

Blanket Implementations

获取 self 的 TypeId。 Read more

从拥有的值中一成不变地借用。 Read more

从拥有的值中借用。 Read more

执行转换。

执行转换。

获得所有权后的结果类型。

通常通过克隆从借用数据中创建拥有的数据。 Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into #41263)

recently added

使用借来的数据来替换拥有的数据,通常是通过克隆。 Read more

发生转换错误时返回的类型。

执行转换。

发生转换错误时返回的类型。

执行转换。