互斥器

1,多个线程使用互斥器Arc

use std::sync::{Mutex, Arc};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let new_counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut mun = new_counter.lock().unwrap();
            *mun += 1;
        });

        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
    println!("result = {}", *counter.lock().unwrap())
}

你可能感兴趣的:(互斥器)