Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Arc

스레드 간의 공유 소유권이 필요한 경우, Arc(원자적 참조 횟수 계산, Atomically Reference Counted)를 사용할 수 있습니다. 이 구조체는 Clone 구현을 통해 힙 메모리에 있는 값의 위치를 가리키는 참조 포인터를 생성하고 참조 횟수를 증가시킵니다. 스레드 간에 소유권을 공유하므로, 값에 대한 마지막 참조 포인터가 스코프를 벗어날 때 변수가 해제됩니다.

use std::time::Duration;
use std::sync::Arc;
use std::thread;

fn main() {
    // 이 변수 선언에서 값이 지정됩니다.
    let apple = Arc::new("같은 사과");

    for _ in 0..10 {
        // 여기서는 힙 메모리의 참조를 가리키는 포인터이므로 별도의 값 지정이 없습니다.
        let apple = Arc::clone(&apple);

        thread::spawn(move || {
            // `Arc`를 사용했으므로, `Arc` 변수 포인터 위치에 할당된 값을 사용하여 스레드를 생성할 수 있습니다.
            println!("{:?}", apple);
        });
    }

    // 모든 `Arc` 인스턴스가 생성된 스레드에서 출력되도록 합니다.
    thread::sleep(Duration::from_secs(1));
}