Skip to content

Commit bb3825d

Browse files
author
build
committed
feat:exercises
1 parent a6e90a5 commit bb3825d

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

exercises/smart_pointers/arc1.rs

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,60 @@
2121
//
2222
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.
2323

24-
// I AM NOT DONE
24+
#![forbid(unused_imports)] // Do not change this, (or the next) line.
25+
use std::sync::Arc;
26+
use std::thread;
27+
28+
fn main() {
29+
let numbers: Vec<_> = (0..100u32).collect();
30+
let shared_numbers = Arc::new(numbers);
31+
let mut joinhandles = Vec::new();
32+
33+
for offset in 0..8 {
34+
let child_numbers = Arc::clone(&shared_numbers);
35+
joinhandles.push(thread::spawn(move || {
36+
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
37+
println!("Sum of offset {} is {}", offset, sum);
38+
}));
39+
}
40+
for handle in joinhandles.into_iter() {
41+
handle.join().unwrap();
42+
}
43+
}
44+
// arc1.rs
45+
//
46+
// In this exercise, we are given a Vec of u32 called "numbers" with values
47+
// ranging from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] We would like to use this
48+
// set of numbers within 8 different threads simultaneously. Each thread is
49+
// going to get the sum of every eighth value, with an offset.
50+
//
51+
// The first thread (offset 0), will sum 0, 8, 16, ...
52+
// The second thread (offset 1), will sum 1, 9, 17, ...
53+
// The third thread (offset 2), will sum 2, 10, 18, ...
54+
// ...
55+
// The eighth thread (offset 7), will sum 7, 15, 23, ...
56+
//
57+
// Because we are using threads, our values need to be thread-safe. Therefore,
58+
// we are using Arc. We need to make a change in each of the two TODOs.
59+
//
60+
// Make this code compile by filling in a value for `shared_numbers` where the
61+
// first TODO comment is, and create an initial binding for `child_numbers`
62+
// where the second TODO comment is. Try not to create any copies of the
63+
// `numbers` Vec!
64+
//
65+
// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint.
2566

2667
#![forbid(unused_imports)] // Do not change this, (or the next) line.
2768
use std::sync::Arc;
2869
use std::thread;
2970

3071
fn main() {
3172
let numbers: Vec<_> = (0..100u32).collect();
32-
let shared_numbers = // TODO
73+
let shared_numbers = Arc::new(numbers);
3374
let mut joinhandles = Vec::new();
3475

3576
for offset in 0..8 {
36-
let child_numbers = // TODO
77+
let child_numbers = Arc::clone(&shared_numbers);
3778
joinhandles.push(thread::spawn(move || {
3879
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
3980
println!("Sum of offset {} is {}", offset, sum);

0 commit comments

Comments
 (0)