Created
April 6, 2015 15:28
-
-
Save ybur-yug/6e10326b2799e20d0542 to your computer and use it in GitHub Desktop.
This file contains 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
extern crate threadpool; | |
use threadpool::ScopedPool; | |
fn main() { | |
let mut numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
{ | |
let pool = ScopedPool::new(4); | |
for x in &mut numbers[..] { | |
pool.execute(move || { | |
*x += 1; | |
}); | |
} | |
} | |
println!("{:?}", numbers); | |
} | |
// This allocates a mutable array on the stack, and then creates a threadpool which adds one to each element of the array, four | |
// threads at a time. We need the inner {}s so that we know that the pool is done working before we try to print the result. Yes, | |
// mutable pointers into the parent stack frame. But, the compiler can verify that this is absolutely safe. Say, for example, that we | |
// left off the inner scope, so that the pool might not be destroyed and therefore join before we try to print out the array. | |
// That'd be racy in most languages. In Rust, it's a compile-time error: | |
error: cannot borrow `numbers` as immutable because it is also borrowed as | |
mutable | |
println!("{:?}", numbers); | |
^~~~~~~ | |
note: previous borrow of `numbers` occurs here; the mutable borrow prevents | |
subsequent moves, borrows, or modification of `numbers` until the borrow | |
ends | |
for x in &mut numbers[..] { | |
^~~~~~~ | |
note: previous borrow ends here | |
fn main() { | |
} | |
^ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment