Skip to content

guide-tasks: Simplify Arc usage to match Arc docs. #14235

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 16, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 11 additions & 27 deletions src/doc/guide-tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,12 +343,9 @@ fn main() {
let numbers_arc = Arc::new(numbers);

for num in range(1u, 10) {
let (tx, rx) = channel();
tx.send(numbers_arc.clone());
let task_numbers = numbers_arc.clone();

spawn(proc() {
let local_arc : Arc<Vec<f64>> = rx.recv();
let task_numbers = &*local_arc;
println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
});
}
Expand All @@ -369,40 +366,27 @@ let numbers_arc=Arc::new(numbers);
# }
~~~

and a clone of it is sent to each task
and a unique clone is captured for each task via a procedure. This only copies the wrapper and not
it's contents. Within the task's procedure, the captured Arc reference can be used as an immutable
reference to the underlying vector as if it were local.

~~~
# extern crate sync;
# extern crate rand;
# use sync::Arc;
# fn pnorm(nums: &[f64], p: uint) -> f64 { 4.0 }
# fn main() {
# let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
# let numbers_arc = Arc::new(numbers);
# let (tx, rx) = channel();
tx.send(numbers_arc.clone());
# }
~~~

copying only the wrapper and not its contents.

Each task recovers the underlying data by

~~~
# extern crate sync;
# extern crate rand;
# use sync::Arc;
# fn main() {
# let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
# let numbers_arc=Arc::new(numbers);
# let (tx, rx) = channel();
# tx.send(numbers_arc.clone());
# let local_arc : Arc<Vec<f64>> = rx.recv();
let task_numbers = &*local_arc;
# let num = 4;
let task_numbers = numbers_arc.clone();
spawn(proc() {
// Capture task_numbers and use it as if it was the underlying vector
println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
});
# }
~~~

and can use it as if it were local.

The `arc` module also implements Arcs around mutable data that are not covered here.

# Handling task failure
Expand Down