Reputation: 415
I'm writing a small game in Rust to learn about multithreading. I got code that contains two loops, one with the logic, one with the rendering, like this:
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;
}
}
}
This code works, but it is pretty much behaving the same way as single thread would. Behavior I want is that at line marked [1], if there is a event iterator waiting, get it, but if there isn't just give me a None and keep going. How do I do that?
Upvotes: 1
Views: 176
Reputation: 127951
I think you need try_recv()
:
let events = match t1_event_out.try_recv() {
Ok(events) => events,
Err(TryRecvError::Empty) => continue,
Err(TryRecvError::Disconnected) => break,
};
Upvotes: 2