mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-22 11:36:23 +00:00
52 lines
838 B
Markdown
52 lines
838 B
Markdown
|
---
|
||
|
id: 6e53ba2a-20e7-4d81-8047-8eecaffc76f7
|
||
|
title: Rust Shared-State Concurrency
|
||
|
---
|
||
|
|
||
|
# Mutex\<T\>
|
||
|
|
||
|
## Single thread example
|
||
|
|
||
|
``` rust
|
||
|
use std::sync::Mutex;
|
||
|
|
||
|
fn main() {
|
||
|
let m = Mutex::new(5);
|
||
|
|
||
|
{
|
||
|
let mut num = m.lock().unwrap();
|
||
|
*num = 6;
|
||
|
}
|
||
|
|
||
|
println!("m = {:?}", m);
|
||
|
}
|
||
|
```
|
||
|
|
||
|
## Multiple thread example
|
||
|
|
||
|
``` rust
|
||
|
use std::sync::{Arc, Mutex};
|
||
|
use std::thread;
|
||
|
|
||
|
fn main() {
|
||
|
let counter = Arc::new(Mutex::new(0));
|
||
|
let mut handles = vec![];
|
||
|
|
||
|
for _ in 0..10 {
|
||
|
let counter = Arc::clone(&counter);
|
||
|
let handle = thread::spawn(move || {
|
||
|
let mut num = counter.lock().unwrap();
|
||
|
|
||
|
*num += 1;
|
||
|
});
|
||
|
handles.push(handle);
|
||
|
}
|
||
|
|
||
|
for handle in handles {
|
||
|
handle.join().unwrap();
|
||
|
}
|
||
|
|
||
|
println!("Result: {}", *counter.lock().unwrap());
|
||
|
}
|
||
|
```
|