Even references and pointers can be sent over a channel, like in this example:
// see code from Chapter 9/code/channel_box.rs use std::thread; use std::sync::mpsc; trait Message : Send { fn print(&self); } struct Msg1 { value: i32 } impl Message for Msg1 { fn print(&self) { println!("value: {:?}", self.value); } } fn main() { let (tx, rx) = mpsc::channel::<Box<Message>>(); let handle = thread::spawn(move|| { let msg = rx.recv().unwrap(); msg.print(); }); let msg = Box::new(Msg1{ value:1 }); tx.send(msg).unwrap(); handle.join().ok(); }
This prints out the following:
value: 1
Exercise:
Make a program, shared_channel.rs, that lets any number of threads share a channel to send in a value, and one receiver that collects all the values.
(Hint: use clone() to give each thread access to the sending endpoint tx. See the example code in Chapter 9/exercises/shared_channel.rs.)
Make a program, shared_channel.rs, that lets any number of threads share a channel to send in a value, and one receiver that collects all the values.
(Hint: use clone() to give each thread access to the sending endpoint tx. See the example code in Chapter 9/exercises/shared_channel.rs.)