Skip to content

Instantly share code, notes, and snippets.

@jakejscott
Last active December 23, 2017 02:42
Show Gist options
  • Save jakejscott/84d1ef54db64c69ff3cc to your computer and use it in GitHub Desktop.
Save jakejscott/84d1ef54db64c69ff3cc to your computer and use it in GitHub Desktop.
rust channels and threads
use std::thread;
use std::sync::mpsc::channel;
use std::sync::mpsc::sync_channel;
// Create a simple streaming channel
fn example1() {
// (tx for transmission)
// (rx for receiving)
let (tx, rx) = channel();
// the spawned thread is "detached" from the current thread. This means it can
// outlive it's partent (the thread that spawned it), unless the parent thread
// is the main thread.
thread::spawn(move|| {
tx.send(10).unwrap();
});
let x = rx.recv().unwrap();
println!("{:?}", x);
}
// Create a shared channel that can be sent along from many threads
// where tx is the sending half (tx for transmission), and rx is the receiving
fn example2() {
let (tx, rx) = channel();
for i in 0..10 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(i).unwrap();
});
}
for _ in 0..10 {
let j = rx.recv().unwrap();
println!("{:?}", j);
}
}
fn example3() {
let (tx, rx) = sync_channel::<i32>(0);
thread::spawn(move || {
println!("Enter");
tx.send(53).unwrap();
println!("Exit");
});
println!("Waiting...");
thread::sleep_ms(3000);
let x = rx.recv().unwrap();
println!("{:?}", x);
thread::sleep_ms(1000);
}
fn mutate_vec(vec: &mut Vec<i32>) {
vec.push(300);
vec.push(400);
println!("{:?}", vec);
}
fn main() {
example1();
example2();
example3();
// The "guard" ensures that the parent thread joins (waits on) its child, by
// performing an implict join in its destructor
let mut vec = Vec::new();
vec.push(100);
vec.push(200);
let guard = thread::scoped(|| {
println!("Waiting for child");
thread::sleep_ms(2000);
mutate_vec(&mut vec);
println!("Child finished");
});
println!("Join guard is waiting on child");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment