我正在Rust写一个小游戏来学习多线程。我得到的代码包含两个循环,一个包含逻辑,一个包含渲染,如下所示:
let (t1_entity_in, t1_entity_out) = mpsc::channel(); // ommited type definitions
let (t1_event_in, t1_event_out) = mpsc::channel();
let entity = Entity::new(20,20);
std::thread::spawn(move || {
let window = Window::new(1280,720);
loop {
// waits until parent send data
let entity = t1_entity_out.recv().unwrap();
window.draw(entity);
window.flip();
let events = window.get_events();
// parent starts working
}
});
'event_loop: loop {
// do stuff to the entity
t1_entity_in.send(entity.clone());
// thread 1 starts workinng
// waits until thread 1 sends data
let events = t1_event_out.recv().unwrap(); // [1]
// thread 1 sent data, continues.
for event in events {
if event.type == event::QUIT {
break 'event_loop;
}
}
}
此代码有效,但它的行为与单线程的行为相同。我想要的行为是在标记为[1]的行,如果有一个事件迭代器在等待,那么就得到它,但是如果没有,那就给我一个None并继续。我该怎么做?
答案 0 :(得分:2)
我认为你需要try_recv()
:
let events = match t1_event_out.try_recv() {
Ok(events) => events,
Err(TryRecvError::Empty) => continue,
Err(TryRecvError::Disconnected) => break,
};