0
0
Rustprogramming~30 mins

Shared state overview in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Shared state overview
📖 Scenario: Imagine you are building a simple counter app where multiple parts of your program need to access and update the same number. This shared number is called the shared state. In Rust, managing shared state safely is important to avoid bugs.
🎯 Goal: You will create a shared counter using Rust's Arc and Mutex types. This will let multiple parts of your program safely read and update the same number.
📋 What You'll Learn
Create a shared counter variable using Arc and Mutex
Create a helper variable to clone the shared counter
Use a block to lock and update the counter value
Print the updated counter value
💡 Why This Matters
🌍 Real World
Shared state is common in programs that have multiple parts working together, like web servers or games, where many pieces need to read and update the same data safely.
💼 Career
Understanding shared state and safe concurrency is important for Rust developers working on multi-threaded applications, ensuring programs run correctly without crashes or data errors.
Progress0 / 4 steps
1
Create the shared counter
Create a variable called counter that holds an Arc wrapping a Mutex containing the number 0. Use std::sync::Arc and std::sync::Mutex.
Rust
Hint

Use Arc::new(Mutex::new(0)) to create the shared counter.

2
Clone the shared counter
Create a variable called counter_clone by cloning the counter variable using Arc::clone(&counter).
Rust
Hint

Use Arc::clone(&counter) to create a new reference to the shared counter.

3
Lock and update the counter
Use a block to lock and update the counter value. Inside the block, use a let mut statement with counter_clone.lock().unwrap() to get a mutable reference called num. Then add 1 to *num.
Rust
Hint

Wrap the lock and update in a block to release the lock automatically: { let mut num = counter_clone.lock().unwrap(); *num += 1; }

4
Print the updated counter
Print the message "Counter value: {}" using println! and the value inside counter. Use lock().unwrap() to access the value.
Rust
Hint

Use println!("Counter value: {}", *counter.lock().unwrap()) to show the current count.