我有一个动态集合futures::sync::mpsc::Sender
,我想为每个传入连接向他们每个人发送一条消息。
我可以使用它UnboundedSender
,因为我可以这样做(见下文)但Sender
会消耗自己,所以我需要将其删除并重新插入Vec
发送后。我怎样才能做到这一点?如果Sender
阻塞,它不应该发送更多消息,而是切换到处理接收器上的传入连接。
这UnboundedSender
实现如下,否则我失败的尝试会被内联注释掉(只需将前面的行替换为注释掉的行)
UnboundedSender (作品)
extern crate tokio;
use tokio::runtime::current_thread;
extern crate futures;
use futures::{stream, Stream, Sink};
use futures::sync::mpsc;
fn main() {
let values = vec![1 as i8, 2, 0, 1, 2, 3, 0, 1, 2, 3, -1];
let mut senders = Vec::<mpsc::UnboundedSender<i8>>::new();
let stream = stream::iter_ok::<_, ()>(values)
.for_each(|v| {
match v {
0 => {
println!("Adding channel");
let (sender, receiver) = mpsc::unbounded();
senders.push(sender);
current_thread::spawn(receiver.for_each(|v| {
println!("Received {}", v);
Ok(())
}))
},
-1 => {
println!("Closing channels");
senders.clear();
},
x => {
for sender in senders.iter() {
println!("Sending {}", x);
sender.unbounded_send(x).unwrap();
}
},
}
Ok(())
});
current_thread::block_on_all(stream)
.expect("Failed to run stream");
println!("Done!");
}
发件人(无效)
extern crate tokio;
use tokio::runtime::current_thread;
extern crate futures;
use futures::{stream, Stream, Sink};
use futures::sync::mpsc;
fn main() {
let values = vec![1 as i8, 2, 0, 1, 2, 3, 0, 1, 2, 3, -1];
let mut senders = Vec::<mpsc::Sender<i8>>::new();
let stream = stream::iter_ok::<_, ()>(values)
.for_each(|v| {
match v {
0 => {
println!("Adding channel");
let (sender, receiver) = mpsc::channel(1);
senders.push(sender);
current_thread::spawn(receiver.for_each(|v| {
println!("Received {}", v);
Ok(())
}))
},
-1 => {
println!("Closing channels");
senders.clear();
},
x => {
for sender in senders.iter() {
println!("Sending {}", x);
sender.send(x);
//^error[E0507]: cannot move out of borrowed content
}
},
}
Ok(())
});
current_thread::block_on_all(stream)
.expect("Failed to run stream");
println!("Done!");
}