What are idiomatic ways to send data between threads?

后端 未结 2 1312
逝去的感伤
逝去的感伤 2020-12-21 00:59

I want to do some calculation in a separate thread, and then recover the data from the main thread. What are the canonical ways to pass some data from a thread to another in

2条回答
  •  死守一世寂寞
    2020-12-21 01:07

    The idiomatic way to do so is to use a channel. It conceptually behaves like an unidirectional tunnel: you put something in one end and it comes out the other side.

    use std::sync::mpsc::channel;
    
    fn main() {
        let (sender, receiver) = channel();
    
        let handle = std::thread::spawn(move || {
            sender.send(String::from("Hello world!")).unwrap();
        });
    
        let data = receiver.recv().unwrap();
        println!("Got {:?}", data);
    
        handle.join().unwrap();
    }
    

    The channel won't work anymore when the receiver is dropped.

    They are mainly 3 ways to recover the data:

    • recv will block until something is received
    • try_recv will return immediately. If the channel is not closed, it is either Ok(data) or Err(TryRevcError::Empty).
    • recv_timeout is the same as try_recv but it waits to get a data a certain amount of time.

提交回复
热议问题