我正在使用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
版本来使用它。
克隆是唯一的解决办法吗?我们能在不克隆通道的发送方的情况下实现同样的目标吗?
发布于 2019-02-06 03:41:58
我们能在不克隆通道的发送方的情况下实现同样的目标吗?
不是的。这就是如何共享Sender
,并且没有其他安全的方法来实现它。
通道通过将共享资源包装在Arc
中来管理共享资源,这样就可以在线程之间安全地共享它们。Sender
的克隆方法涉及到一些逻辑,但最终它是关于克隆那些Arc
的--这就是Arc
的共享方式。
克隆一个Arc
很便宜,而且很可能你不应该担心,除非你是在一个紧密的循环中克隆它们。一旦它们被克隆,Arc
的开销就很小--每个克隆本质上都是一个指针。
https://stackoverflow.com/questions/54552165
复制相似问题