Skip to content

Instantly share code, notes, and snippets.

@maghoff
Created November 2, 2015 18:38
Show Gist options
  • Save maghoff/3608700fd903aabad780 to your computer and use it in GitHub Desktop.
Save maghoff/3608700fd903aabad780 to your computer and use it in GitHub Desktop.
Threads and scoping in rust
#![feature(scoped)]
use std::thread;
fn greet(peeps: &str) {
println!("Hello, {}", peeps);
}
fn indirect(peeps: &str) {
// In this case, `peeps` outlives the thread, but Rust does not
// realize. We have to make a copy that we can send to the thread.
// Comment out the next line to make this function fail compilation
let peeps = peeps.to_string();
thread::spawn(move || greet(&peeps)).join().unwrap();
}
fn indirect_scoped(peeps: &str) {
// In this case, Rust realizes that the thread cannot outlive the scope
// of `peeps`. This is the functionality of `thread::scoped`.
thread::scoped(move || greet(&peeps)).join();
// Problem: `thread::scoped` is deprecated (for good reason).
}
fn main() {
let a = "World";
greet(a); // Normal borrowing
// Calling `greet` from a thread works fine:
thread::spawn(|| greet("Threads")).join().unwrap();
// Borrowing `a` into a thread works fine from `main`, since the
// lifetime of `main` is `'static`. We have to add the `move`.
thread::spawn(move || greet(a)).join().unwrap();
indirect(a);
indirect_scoped(a);
}
@maghoff
Copy link
Author

maghoff commented Nov 2, 2015

The question is, can I use peeps in a thread in a function other than main without making a copy or using a deprecated feature?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment