최대 1 분 소요

개요

  • 타입 시스템과 소유권 규칙으로 인해 락 사용의 안정성 보장


예제

  • 코드

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

        fn main() {
            let arc_mutex = Arc::new(Mutex::new(0));

            let mut handles = vec![];

            for _i in 0..5 {
                let mutex = Arc::clone(&arc_mutex);
                handles.push(thread::spawn(move || {
                    let mut n = mutex.lock().unwrap();
                    println!("1 : {}", *n);
                    *n += 1;
                    thread::sleep(Duration::from_millis(500));
                }));

                let mutex = Arc::clone(&arc_mutex);
                handles.push(thread::spawn(move || {
                    let mut n = mutex.lock().unwrap();
                    println!("2 : {}", *n);
                    *n += 1;
                    thread::sleep(Duration::from_millis(500));
                }));
            }

            for handle in handles {
                handle.join().unwrap();
            }
        }
  • 실행 결과

        1 : 0
        2 : 1
        2 : 2
        1 : 3
        2 : 4
        2 : 5
        1 : 6
        2 : 7
        1 : 8
        1 : 9