@@ -162,7 +162,7 @@ The same [ownership system](ownership.html) that helps prevent using pointers
162
162
incorrectly also helps rule out data races, one of the worst kinds of
163
163
concurrency bugs.
164
164
165
- As an example, here is a Rust program that could have a data race in many
165
+ As an example, here is a Rust program that would have a data race in many
166
166
languages. It will not compile:
167
167
168
168
``` ignore
@@ -174,7 +174,7 @@ fn main() {
174
174
175
175
for i in 0..3 {
176
176
thread::spawn(move || {
177
- data[i ] += 1 ;
177
+ data[0 ] += i ;
178
178
});
179
179
}
180
180
@@ -186,7 +186,7 @@ This gives us an error:
186
186
187
187
``` text
188
188
8:17 error: capture of moved value: `data`
189
- data[i ] += 1 ;
189
+ data[0 ] += i ;
190
190
^~~~
191
191
```
192
192
@@ -195,11 +195,6 @@ thread, and the thread takes ownership of the reference, we'd have three owners!
195
195
` data ` gets moved out of ` main ` in the first call to ` spawn() ` , so subsequent
196
196
calls in the loop cannot use this variable.
197
197
198
- Note that this specific example will not cause a data race since different array
199
- indices are being accessed. But this can't be determined at compile time, and in
200
- a similar situation where ` i ` is a constant or is random, you would have a data
201
- race.
202
-
203
198
So, we need some type that lets us have more than one owning reference to a
204
199
value. Usually, we'd use ` Rc<T> ` for this, which is a reference counted type
205
200
that provides shared ownership. It has some runtime bookkeeping that keeps track
@@ -223,7 +218,7 @@ fn main() {
223
218
224
219
// use it in a thread
225
220
thread::spawn(move || {
226
- data_ref[i ] += 1 ;
221
+ data_ref[0 ] += i ;
227
222
});
228
223
}
229
224
@@ -266,7 +261,7 @@ fn main() {
266
261
for i in 0..3 {
267
262
let data = data.clone();
268
263
thread::spawn(move || {
269
- data[i ] += 1 ;
264
+ data[0 ] += i ;
270
265
});
271
266
}
272
267
@@ -281,7 +276,7 @@ And... still gives us an error.
281
276
282
277
``` text
283
278
<anon>:11:24 error: cannot borrow immutable borrowed content as mutable
284
- <anon>:11 data[i ] += 1 ;
279
+ <anon>:11 data[0 ] += i ;
285
280
^~~~
286
281
```
287
282
@@ -317,7 +312,7 @@ fn main() {
317
312
let data = data . clone ();
318
313
thread :: spawn (move || {
319
314
let mut data = data . lock (). unwrap ();
320
- data [i ] += 1 ;
315
+ data [0 ] += i ;
321
316
});
322
317
}
323
318
@@ -360,7 +355,7 @@ Let's examine the body of the thread more closely:
360
355
# let data = data . clone ();
361
356
thread :: spawn (move || {
362
357
let mut data = data . lock (). unwrap ();
363
- data [i ] += 1 ;
358
+ data [0 ] += i ;
364
359
});
365
360
# }
366
361
# thread :: sleep (Duration :: from_millis (50 ));
0 commit comments