@@ -66,10 +66,14 @@ threads = []
66
66
5_000_000 .times do
67
67
count += 1
68
68
end
69
+
70
+ count
69
71
end
70
72
end
71
73
72
- threads.each { |t | t.join }
74
+ threads.each do |t |
75
+ puts " Thread finished with count=#{ t.value } "
76
+ end
73
77
puts " done!"
74
78
```
75
79
@@ -103,50 +107,26 @@ use std::thread;
103
107
fn process () {
104
108
let handles : Vec <_ > = (0 .. 10 ). map (| _ | {
105
109
thread :: spawn (|| {
106
- let mut _x = 0 ;
110
+ let mut x = 0 ;
107
111
for _ in (0 .. 5_000_000 ) {
108
- _x += 1
112
+ x += 1
109
113
}
114
+ x
110
115
})
111
116
}). collect ();
112
117
113
118
for h in handles {
114
- h . join (). ok (). expect (" Could not join a thread!" );
119
+ println! (" Thread finished with count={}" ,
120
+ h . join (). map_err (| _ | " Could not join a thread!" ). unwrap ());
115
121
}
122
+ println! (" done!" );
116
123
}
117
124
```
118
125
119
126
Some of this should look familiar from previous examples. We spin up ten
120
127
threads, collecting them into a ` handles ` vector. Inside of each thread, we
121
- loop five million times, and add one to ` _x ` each time. Why the underscore?
122
- Well, if we remove it and compile:
123
-
124
- ``` bash
125
- $ cargo build
126
- Compiling embed v0.1.0 (file:///home/steve/src/embed)
127
- src/lib.rs:3:1: 16:2 warning: function is never used: ` process` , # [warn(dead_code)] on by default
128
- src/lib.rs:3 fn process () {
129
- src/lib.rs:4 let handles: Vec< _> = (0..10).map(| _| {
130
- src/lib.rs:5 thread::spawn(|| {
131
- src/lib.rs:6 let mut x = 0;
132
- src/lib.rs:7 for _ in (0..5_000_000) {
133
- src/lib.rs:8 x += 1
134
- ...
135
- src/lib.rs:6:17: 6:22 warning: variable ` x` is assigned to, but never used, # [warn(unused_variables)] on by default
136
- src/lib.rs:6 let mut x = 0;
137
- ^~~~~
138
- ` ` `
139
-
140
- That first warning is because we are building a library. If we had a test
141
- for this function, the warning would go away. But for now, it’s never
142
- called.
143
-
144
- The second is related to ` x` versus ` _x` . Because we never actually _do_
145
- anything with ` x` , we get a warning about it. In our case, that’s perfectly
146
- okay, as we’re just trying to waste CPU cycles. Prefixing ` x` with the
147
- underscore removes the warning.
148
-
149
- Finally, we join on each thread.
128
+ loop five million times, and add one to ` x ` each time. Finally, we join on
129
+ each thread.
150
130
151
131
Right now, however, this is a Rust library, and it doesn’t expose anything
152
132
that’s callable from C. If we tried to hook this up to another language right
0 commit comments