Skip to content

Instantly share code, notes, and snippets.

Created July 29, 2016 09:26
Show Gist options
  • Save anonymous/1d75dd3d0aaefeb694d0ce0638ab4f1f to your computer and use it in GitHub Desktop.
Save anonymous/1d75dd3d0aaefeb694d0ce0638ab4f1f to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::thread::{Thread, JoinHandle, spawn, current};
use std::sync::mpsc::{Sender, channel};
enum Message {
Query(Sender<i32>),
Stop,
}
#[derive(Clone)]
struct Service {
tx: Sender<Message>,
thread: Thread,
}
impl Service {
fn launch() -> (Service, JoinHandle<()>) {
let (launch_tx, launch_rx) = channel();
let join_handle = spawn(move || {
let (tx, rx) = channel();
launch_tx.send((tx, current())).unwrap();
while let Ok(msg) = rx.recv() {
match msg {
Message::Query(s) => {
println!("computing in another thread!");
s.send(42).unwrap()
},
Message::Stop => return (),
}
}
()
});
let (tx, thread) = launch_rx.recv().unwrap();
(Service {
tx: tx,
thread: thread,
}, join_handle)
}
fn do_computation_later(&self, reply_to: Sender<i32>) {
println!("requesting later computation");
self.tx.send(Message::Query(reply_to)).unwrap();
}
fn stop(&self) {
self.tx.send(Message::Stop).unwrap();
}
}
fn main() {
let (service, join_handle) = Service::launch();
let another_join_handle = {
let service = service.clone();
spawn(move || {
let (tx, rx) = channel();
// look, no cloning by the service consumer!
service.do_computation_later(tx);
let ret = rx.recv().unwrap();
println!("computation complete");
return ret;
})
};
println!("joined {:?}", another_join_handle.join());
// also no cloning/locking by consumer
service.stop();
join_handle.join().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment