替代克隆TOKIO信道的发送器,用于期货封闭

问题描述 投票:0回答:1

我与tokiohyper工作产卵几个任务。

// Defining the task
let task = self.some_future_using
            .map(move |resp| println!("OK: {}", resp))
            .map_err(move |e| println!("Error: {}",e));

// Spawning the task
tokio::spawn(task);

而不是简单地记录结果,我想在一个有界TOKIO通道发送的结果。

// Defines the channel
let (tx, rx) = mpsc::channel(10);

// Defining the task
let task = self.some_future_using
            .map(|resp| /* Send Ok(resp) to tx */ )
            .map_err(|e| /* Send Err(e) to tx */);

// Spawning the task
tokio::spawn(task);

由于两个罩可以活得比其中tx定义范围,我们需要克隆和移动tx两个瓶盖:

// Defines the channel
let (tx, rx) = mpsc::channel(10);
let mut tx_ok = tx.clone();
let mut tx_err = tx.clone();

// Defining the task
let task = self.some_future_using
            .map(move |resp| tx_ok.try_send(Ok(())).unwrap() )
            .map_err(move |e| tx_err.try_send(Ok(())).unwrap() );

// Spawning the task
tokio::spawn(task);

在这种情况下更多的逻辑是使用组合程序(mapand_then等)加入,每封需要它自己的克隆tx版本才能使用它。

克隆是唯一的解决办法?我们能不能达到同样没有克隆通道的发件人使用它的每封申报?

concurrency rust rust-tokio
1个回答
0
投票

我们能不能达到同样没有克隆通道的发件人使用它的每封申报?

号这是一个Sender如何共享,并没有另一种安全的方式来做到这一点。

信道管理由在Arcs包裹他们共享资源,这样他们就可以安全地在线程之间共享。有一点参与Sender的克隆方法的逻辑的,但最终是有关克隆那些Arcs - 这是Arcs如何共享。

克隆的Arc便宜,而且很可能不是你应该担心的,除非你是在紧密循环克隆它们。一旦它们被克隆,很少有开销的Arc - 每个克隆本质上是一个指针。

© www.soinside.com 2019 - 2024. All rights reserved.