0
0
Rustprogramming~30 mins

Concurrency safety guarantees in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Concurrency Safety Guarantees in Rust
📖 Scenario: You are building a simple Rust program that shares data between multiple threads safely. Rust's concurrency safety guarantees help prevent bugs like data races.
🎯 Goal: Learn how to use Rust's Arc and Mutex to safely share and update data across threads without causing concurrency issues.
📋 What You'll Learn
Create a shared data structure using Arc and Mutex
Spawn multiple threads that access and modify the shared data
Use locking to ensure safe concurrent access
Print the final value of the shared data after all threads finish
💡 Why This Matters
🌍 Real World
Many real-world programs need to share data safely between multiple threads, such as web servers handling many users or background tasks updating shared state.
💼 Career
Understanding Rust's concurrency safety guarantees is essential for systems programming, embedded development, and any job requiring safe, efficient multi-threaded code.
Progress0 / 4 steps
1
Create a shared counter using Arc and Mutex
Write code to create a variable called counter that is an Arc wrapping a Mutex containing the integer 0. This will be the shared counter for threads.
Rust
Hint

Use Arc::new(Mutex::new(0)) to create a thread-safe shared integer starting at 0.

2
Spawn threads and clone the shared counter
Add code to create a vector called handles to store thread handles. Then spawn 5 threads using std::thread::spawn. Inside the loop, clone the counter using Arc::clone(&counter) and move it into the thread closure.
Rust
Hint

Use a for loop from 0 to 5, clone the counter inside the loop, and spawn threads pushing their handles into handles.

3
Increment the shared counter safely inside each thread
Inside the thread closure, lock the counter mutex using lock().unwrap(). Then increment the value inside the mutex by 1.
Rust
Hint

Use let mut num = counter.lock().unwrap(); to get a mutable reference, then increment with *num += 1;.

4
Wait for threads to finish and print the final counter value
Use a for loop to join all threads in handles. Then lock the counter mutex and print the final value with println!("Final counter: {}", *counter.lock().unwrap()).
Rust
Hint

Use handle.join().unwrap(); to wait for each thread, then print the counter value.