0
0
Rustprogramming~7 mins

Concurrency safety guarantees in Rust

Choose your learning style9 modes available
Introduction

Concurrency safety guarantees help your program avoid mistakes when many parts run at the same time. This keeps your program correct and prevents crashes or wrong results.

When you want to run multiple tasks at the same time to make your program faster.
When you share data between different parts of your program running together.
When you want to avoid bugs caused by two parts changing the same data at once.
When you write programs that handle many users or events at the same time.
When you want your program to be safe and not crash because of concurrent access.
Syntax
Rust
use std::sync::{Arc, Mutex};

let data = Arc::new(Mutex::new(0));
// Arc allows sharing ownership safely
// Mutex allows only one thread to access data at a time

Arc stands for Atomic Reference Counting. It lets multiple parts share ownership safely.

Mutex is a lock that makes sure only one part can change data at once.

Examples
This example shows how to safely increase a number from multiple threads using Arc and Mutex.
Rust
use std::sync::{Arc, Mutex};
use std::thread;

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!("Counter: {}", *counter.lock().unwrap());
RwLock allows multiple readers or one writer at a time, useful for read-heavy data.
Rust
use std::sync::RwLock;

let data = RwLock::new(5);
{
    let r = data.read().unwrap();
    println!("Read data: {}", *r);
}
{
    let mut w = data.write().unwrap();
    *w += 1;
    println!("Updated data: {}", *w);
}
Sample Program

This program creates 10 threads. Each thread safely adds 1 to the shared counter using Mutex and Arc. The final value shows the total increments.

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..10 {
        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 counter value: {}", *counter.lock().unwrap());
}
OutputSuccess
Important Notes

Rust's ownership and type system help catch concurrency mistakes at compile time.

Mutex can cause your program to wait if another part is using the data, so use it carefully.

Arc is needed to share data safely between threads because normal references can't be shared safely.

Summary

Concurrency safety guarantees prevent bugs when multiple parts run at the same time.

Use Arc to share ownership and Mutex or RwLock to control access to shared data.

Rust helps you write safe concurrent code by checking rules before running your program.