简体   繁体   中英

Grabbing data from mpsc::channel without having it lock if there is no data waiting

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?

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,
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM