Skip to content

Commit cf1cf0b

Browse files
committed
Add thread-mutex.rs example to examples folder
1 parent 465c281 commit cf1cf0b

2 files changed

Lines changed: 39 additions & 4 deletions

File tree

_articles/server-sockets.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -415,11 +415,11 @@ fn main() {
415415
for _ in 0..4 {
416416
// Clone the Arc to share ownership between threads.
417417
// The Arc type maintains reference count of the number of copies of the data.
418-
let counter = Arc::clone(&counter);
418+
let clonedcounter = Arc::clone(&counter);
419419

420420
let handle = thread::spawn(move || {
421421
// Lock the mutex before accessing the shared data.
422-
let mut value = counter.lock().unwrap();
422+
let mut value = clonedcounter.lock().unwrap();
423423
*value += 1;
424424
// Mutex is automatically unlocked when `value` goes out of scope
425425
});
@@ -436,9 +436,10 @@ fn main() {
436436
}
437437
```
438438

439+
The same example can be found in our **[git repo](https://github.com/PasiSa/AdvancedNetworking/tree/main/examples/rust/thread-mutex.rs)**.
439440
For testing this kind of simple programs with Rust, you can compile a single
440-
source file using the **rustc** command, e.g. `rustc threadtest.rs`. This would
441-
produce executable called `threadtest` that can be executed on command line to
441+
source file using the **rustc** command, e.g. `rustc thread-mutex.rs`. This would
442+
produce executable called `thread-mutex` that can be executed on command line to
442443
test if it works.
443444

444445
## Efficient file transfer

examples/rust/thread-mutex.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Example from server section on shared state and synchronization
2+
3+
use std::sync::{Arc, Mutex};
4+
use std::thread;
5+
6+
fn main() {
7+
// Shared state: a counter protected by a mutex.
8+
let counter = Arc::new(Mutex::new(0));
9+
10+
// Vector for thread handles.
11+
let mut handles = Vec::new();
12+
13+
for _ in 0..4 {
14+
// Clone the Arc to share ownership between threads.
15+
// The Arc type maintains reference count of the number of copies of the data.
16+
let clonedcounter = Arc::clone(&counter);
17+
18+
let handle = thread::spawn(move || {
19+
// Lock the mutex before accessing the shared data.
20+
let mut value = clonedcounter.lock().unwrap();
21+
*value += 1;
22+
// Mutex is automatically unlocked when `value` goes out of scope
23+
});
24+
25+
handles.push(handle);
26+
}
27+
28+
// Wait for all threads to finish
29+
for handle in handles {
30+
handle.join().unwrap();
31+
}
32+
33+
println!("Final counter value: {}", *counter.lock().unwrap());
34+
}

0 commit comments

Comments
 (0)