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() {
    // This variable declaration is where its value is specified.
    let apple = Arc::new("the same apple");

    for _ in 0..10 {
        // Here there is no value specification as it is a pointer to a
        // reference in the memory heap.
        let apple = Arc::clone(&apple);

        thread::spawn(move || {
            // As Arc was used, threads can be spawned using the value allocated
            // in the Arc variable pointer's location.
            println!("{:?}", apple);
        });
    }

    // Make sure all Arc instances are printed from spawned threads.
    thread::sleep(Duration::from_secs(1));
}