Created
November 2, 2015 18:38
-
-
Save maghoff/3608700fd903aabad780 to your computer and use it in GitHub Desktop.
Threads and scoping in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The question is, can I use
peeps
in a thread in a function other thanmain
without making a copy or using a deprecated feature?