0
0
Rustprogramming~10 mins

Shared state overview in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Shared state overview
Start: Create shared state
Multiple threads access shared state
Use synchronization (Mutex, Arc)
Threads read/write safely
Threads finish work
Shared state dropped
This flow shows how shared state is created, accessed safely by multiple threads using synchronization, and then cleaned up.
Execution Sample
Rust
use std::sync::{Arc, Mutex};
use std::thread;

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

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

    for handle in handles {
        handle.join().unwrap();
    }
}
This code creates a shared counter protected by a mutex and shared safely across threads.
Execution Table
StepActionThreadMutex LockCounter ValueOutput/Note
1Create Arc<Mutex> with 0MainUnlocked0Shared state initialized
2Spawn thread 1Thread 1Lock acquired0Thread 1 locks mutex
3Increment counterThread 1Locked1Counter incremented to 1
4Unlock mutexThread 1Unlocked1Thread 1 releases lock
5Spawn thread 2Thread 2Lock acquired1Thread 2 locks mutex
6Increment counterThread 2Locked2Counter incremented to 2
7Unlock mutexThread 2Unlocked2Thread 2 releases lock
8Spawn thread 3Thread 3Lock acquired2Thread 3 locks mutex
9Increment counterThread 3Locked3Counter incremented to 3
10Unlock mutexThread 3Unlocked3Thread 3 releases lock
11All threads joinedMainUnlocked3Final counter value is 3
💡 All threads finished, shared counter safely incremented to 3
Variable Tracker
VariableStartAfter Thread 1After Thread 2After Thread 3Final
counter (Mutex guard)01233
Arc strong count12221
Key Moments - 3 Insights
Why do we need Arc when sharing state between threads?
Arc allows multiple ownership of the shared state safely across threads, as shown in steps 2, 5, and 8 where threads clone the Arc.
What happens if we try to access the counter without locking the mutex?
Without locking, simultaneous access can cause data races. The mutex lock in steps 2, 5, and 8 ensures only one thread accesses the counter at a time.
Why does the counter value increase step by step instead of all at once?
Each thread locks the mutex, increments the counter, then unlocks it before the next thread accesses it, ensuring safe sequential updates (see steps 3, 6, 9).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the counter value after Thread 2 releases the mutex?
A1
B3
C2
D0
💡 Hint
Check step 7 in the execution table where Thread 2 unlocks the mutex.
At which step does the mutex lock get acquired for the third time?
AStep 6
BStep 8
CStep 3
DStep 10
💡 Hint
Look for the 'Lock acquired' action in the execution table.
If we remove Arc and share Mutex directly, what would happen?
ACompile error due to ownership rules
BRuntime panic due to data race
CCode compiles and runs fine
DCounter never increments
💡 Hint
Arc is needed for multiple ownership across threads, see key moment about Arc.
Concept Snapshot
Shared state in Rust uses Arc for multiple ownership and Mutex for safe access.
Arc clones increase reference count for threads.
Mutex locks prevent data races by allowing one thread at a time.
Threads clone Arc, lock Mutex, modify data, then unlock.
Final shared state is dropped when all owners go out of scope.
Full Transcript
This example shows how Rust manages shared state safely across threads. We start by creating a shared counter wrapped in a Mutex and inside an Arc. The Arc allows multiple threads to own the counter. Each thread clones the Arc to get access. Before changing the counter, a thread locks the mutex to ensure exclusive access. It increments the counter, then unlocks the mutex. This process repeats for each thread. The execution table traces each step: locking, incrementing, unlocking. The variable tracker shows how the counter value changes from 0 to 3. Key moments explain why Arc and Mutex are needed to avoid data races and ownership errors. The visual quiz tests understanding of the counter value at different steps, mutex locking order, and the role of Arc. This approach ensures safe, synchronized shared state in Rust multithreading.