0
0
Rustprogramming~5 mins

Shared state overview in Rust

Choose your learning style9 modes available
Introduction

Shared state lets multiple parts of a program use and change the same data safely. It helps programs work together without mistakes.

When multiple threads need to read and write the same information.
When you want to keep data consistent across different parts of your program.
When you need to share settings or counters between tasks.
When you want to avoid copying data many times.
When you want to coordinate work between different workers.
Syntax
Rust
use std::sync::{Arc, Mutex};

let shared_data = Arc::new(Mutex::new(0));

Arc lets multiple owners share the same data safely across threads.

Mutex makes sure only one thread changes the data at a time.

Examples
Create shared number 5 that many parts can access safely.
Rust
use std::sync::{Arc, Mutex};

let count = Arc::new(Mutex::new(5));
Copy the shared pointer, lock the data to change it, then add 1.
Rust
let data = Arc::clone(&count);
let mut num = data.lock().unwrap();
*num += 1;
Sample Program

This program creates a shared number starting at 0. Five threads each add 1 safely. At the end, it prints the total count.

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..5 {
        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();
    }

    println!("Final count: {}", *counter.lock().unwrap());
}
OutputSuccess
Important Notes

Always lock the Mutex before accessing the data to avoid errors.

Arc helps share ownership safely between threads.

Be careful to avoid deadlocks by locking only when needed and unlocking quickly.

Summary

Shared state lets many parts use the same data safely.

Use Arc to share ownership and Mutex to control access.

This helps avoid mistakes when multiple threads work together.