gpt4 book ai didi

rust - 选择动态创建的 channel

转载 作者:行者123 更新时间:2023-11-29 08:09:53 25 4
gpt4 key购买 nike

我有:

use std::collections::{DList, Deque, TreeMap};
use std::comm::{Select, Handle};

fn main() {
let mut list = DList::new();
let mut handles = TreeMap::new();

let select = Select::new();

for i in range(0, 3i) {

// Create channel
let (tx, rx) = channel();

// Move receiver inside dlist
list.push_front(rx);

// Get the mut ref from the dlist
let mut nrx = list.front_mut().unwrap();

let handle = select.handle(nrx);
let id = handle.id();
handles.insert(id, handle);

// Get the mut ref from the map and add to select
unsafe { handles.find_mut(&id).unwrap().add(); }

spawn(proc() {
// Work with the channel
let sender = tx;
});

}

loop {
let selected = select.wait();
println!("Selected channel id: {}", selected);
}

}

我得到的错误是:

<anon>:21:22: 21:40 error: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
<anon>:21 let handle = select.handle(nrx);
^~~~~~~~~~~~~~~~~~
<anon>:21:22: 21:28 note: first, the lifetime must be contained by the expression at 21:21...
<anon>:21 let handle = select.handle(nrx);
^~~~~~
<anon>:21:22: 21:28 note: ...so that automatically reference is valid at the time of borrow
<anon>:21 let handle = select.handle(nrx);
^~~~~~
<anon>:21:36: 21:39 note: but, the lifetime must also be contained by the expression at 21:35...
<anon>:21 let handle = select.handle(nrx);
^~~
<anon>:21:36: 21:39 note: ...so that automatically reference is valid at the time of borrow
<anon>:21 let handle = select.handle(nrx);
^~~
error: aborting due to previous error
playpen: application terminated with error code 101

和 play.rust-lang 链接:http://is.gd/N1cF42 .

更改代码以在每个调用 try_recv 的代码中使用 Vec 和 iter,因为开发人员告诉我 select 还没有为此做好准备(还没有?),但想知道哪些是其他解决方案或开发人员如何处理它。

最佳答案

找到这个库 https://github.com/mahkoh/comm它有许多 channel 实现,也可以(安全地)选择编译时未知的 channel 。来自文档:

use std::thread::{Thread};
use std::old_io::{timer};
use std::time::duration::{Duration};
use comm::{spsc};
use comm::select::{Select, Selectable};

let mut channels = vec!();
for i in 0..10 {
let (send, recv) = spsc::one_space::new();
channels.push(recv);
Thread::spawn(move || {
timer::sleep(Duration::milliseconds(100));
send.send(i).ok();
});
}
let select = Select::new();
for recv in &channels {
select.add(recv);
}
let first_ready = select.wait(&mut [0])[0];
for recv in &channels {
if first_ready == recv.id() {
println!("First ready: {}", recv.recv_sync().unwrap());
return;
}
}

关于rust - 选择动态创建的 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24872236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com