シングルスレッド
mutexのデータにアクセスするには、lockメソッドを使用してロックを獲得する
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
}
println!("m= {:?}", m);
}
スレッド間でsemaforeを利用しようとするとエラーになる。
use std::sync::{Mutex, Arc};
use std::thread;
use rand::Rng;
use std_semaphore::Semaphore;
use std::time::Duration;
static TOTAL_SPOTS: u32 = 3;
fn main() {
let parked_cars = Arc::new(Mutex::new(0));
let mut handles = vec![];
let sem = Semaphore::new(TOTAL_SPOTS.try_into().unwrap());
for _ in 0..10 {
let counter = Arc::clone(&parked_cars);
let handle = thread::spawn(move || {
let mut rng = rand::thread_rng();
// enter
sem.acquire();
let mut num = counter.lock().unwrap();
*num += 1;
thread::sleep(Duration::from_millis(rng.gen_range(1..10)));
// exit
sem.release();
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *parked_cars.lock().unwrap());
}
15 | for _ in 0..10 {
| ————– inside of this loop
…
19 | let handle = thread::spawn(move || {
| ^^^^^^^ value moved into closure here, in previous iteration of loop
…
23 | sem.acquire();
| — use occurs due to use in closure
中々奥が深い..