-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path15-shared-counter.rs
69 lines (59 loc) · 1.77 KB
/
15-shared-counter.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// -----------------------------------------------------------------------------
// Atelier Rust
// 2019-11-17 - 14h -> 16h
// Animateur: Axel (darnuria) && Aurelia
//
// 10-shared-counter.rs
//
// Objectifs pédagogiques:
//
// - Multi-threading les bases
// - Mécanismes de partages
// - move/borrow et threads
//
// /!\ Quand vous verrez les symboles: `???`, il s'agit de code à
// compléter soi-même c'est normal que Rust indique une erreur! :)
// -----------------------------------------------------------------------------
use std::thread;
use std::sync::{Arc, Mutex};
struct SharedCounter {
counter: i32,
}
impl SharedCounter {
fn new() -> SharedCounter {
SharedCounter { counter: 0 }
}
#[inline]
fn value(&self) -> i32 {
self.counter
}
fn increment(&mut self) {
self.counter += 1;
}
}
fn main() {
let counter = SharedCounter::new();
let mut threads = Vec::new();
println!("Main: create 3 threads!");
for i in 0..3 {
// let counter = Arc::clone(&counter);
println!("Arthas (main): Thread {} I raise you from the grave.", i + 2);
let thread = thread::spawn(move || {
let tid = thread::current().id();
println!("Thread <{:?}>: I'am ready.", tid);
for _ in 0..10000 {
// let mut counter = counter
// .lock()
// .expect("Whops cannot acquire lock.");
counter.increment();
}
println!("Thread <{:?}>: I'am done.", tid);
});
threads.push(thread);
}
for t in threads {
t.join().expect("Unable to join!");
}
// let counter = counter.lock().expect("It is fine.");
println!("Counter end of program: {}.", counter.value())
}