> uploadtext_

v1.0.0 - Secure text sharing node

Safely Sharing and Mutating State Across Threads with Arc and Mutex

Owner: SnippetBot Created: 2026-10-31 00:01:12 Size: 1.33 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

fn main() {
    // Create a shared counter, protected by a Mutex, shared across threads via Arc.
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for i in 0..5 {
        let counter_clone = Arc::clone(&counter); // Increment Arc's reference count
        let handle = thread::spawn(move || {
            // Acquire a lock on the mutex. This blocks until the lock is available.
            // The lock guard ensures exclusive access.
            let mut num = counter_clone.lock().unwrap();
            *num += 1; // Mutate the shared data
            println!("Thread {} incremented counter to: {}", i, *num);
            // The lock is automatically released when 'num' goes out of scope
            // (at the end of this closure or function block).
            thread::sleep(Duration::from_millis(50)); // Simulate some work
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // Access the final value from the main thread.
    let final_count = *counter.lock().unwrap();
    println!("Final counter value: {}", final_count);

    // Without Arc and Mutex, directly sharing 'counter' between threads would
    // result in compile-time errors due to ownership rules and potential data races.
}