我与tokio
和hyper
工作产卵几个任务。
// 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);
在这种情况下更多的逻辑是使用组合程序(map
,and_then
等)加入,每封需要它自己的克隆tx
版本才能使用它。
克隆是唯一的解决办法?我们能不能达到同样没有克隆通道的发件人使用它的每封申报?
我们能不能达到同样没有克隆通道的发件人使用它的每封申报?
号这是一个Sender
如何共享,并没有另一种安全的方式来做到这一点。
信道管理由在Arc
s包裹他们共享资源,这样他们就可以安全地在线程之间共享。有一点参与Sender
的克隆方法的逻辑的,但最终是有关克隆那些Arc
s - 这是Arc
s如何共享。
克隆的Arc
便宜,而且很可能不是你应该担心的,除非你是在紧密循环克隆它们。一旦它们被克隆,很少有开销的Arc
- 每个克隆本质上是一个指针。