Day 28: Explore shared-state concurrency with Mutex and RwLock.

Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
Search for a command to run...

Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
No comments yet. Be the first to comment.
Move beyond traditional RESTful thinking. Learn how to design APIs specifically for MCP (Model Context Protocol) servers. This guide covers the shift in mindset, a practical OpenAPI 3.1 example, and a Spring Boot implementation to make your services ...

Extending Kestra to Every Corner of Your Data Stack. Introduction: The Power of Plugins Imagine you're a master chef. You don't just have one knife - you have specialized tools for every task: a paring knife for delicate work, a chef's knife for chop...
Mastering Complex Orchestration Scenarios. Introduction: The Orchestrator's Toolkit Imagine you're conducting a symphony. You don't just wave your baton - you cue sections, adjust tempo, handle surprises, and ensure harmony. That's what advanced work...
From Data Extraction to Loading - A Practical Guide Introduction: Why ETL Still Matters in the Modern Data Stack Remember when data engineering was "extract, transform, load"? Some say ETL is dead, replaced by ELT, reverse ETL, and data mesh. But her...
Building Blocks of Declarative Orchestration. Introduction: The Power of Simplicity Imagine trying to build a house without understanding bricks, beams, and blueprints. That's what using an orchestration tool without understanding its core concepts f...
On Day 28, let's delve into shared-state concurrency using Mutex (Mutual Exclusion) and RwLock (Read-Write Lock) in Rust. These synchronization primitives help manage access to shared data among multiple threads.
Mutex provides exclusive access to shared data by allowing only one thread to acquire the lock at a time. It ensures that the data remains consistent while being accessed by multiple threads.
use std::sync::Mutex;
use std::thread;
fn main() {
let data = Mutex::new(0);
let handle = thread::spawn(move || {
let mut num = data.lock().unwrap();
*num += 1;
});
handle.join().expect("Thread panicked!");
println!("Data: {:?}", data.lock().unwrap());
}
RwLock allows multiple threads to acquire read access simultaneously but enforces exclusive access for write operations. This enables multiple readers or a single writer at a time, ensuring data consistency.
use std::sync::{RwLock, Arc};
use std::thread;
fn main() {
let data = Arc::new(RwLock::new(0));
let mut handles = vec![];
for _ in 0..5 {
let data = Arc::clone(&data);
let handle = thread::spawn(move || {
let num = data.read().unwrap();
println!("Read Data: {}", *num);
});
handles.push(handle);
}
let write_handle = thread::spawn(move || {
let mut num = data.write().unwrap();
*num = 42;
});
handles.into_iter().for_each(|h| h.join().expect("Thread panicked!"));
write_handle.join().expect("Write thread panicked!");
println!("Final Data: {:?}", *data.read().unwrap());
}
Mutex and RwLock are crucial synchronization primitives in Rust for managing shared-state concurrency. While Mutex provides exclusive access for both reading and writing, RwLock allows multiple readers or a single writer, balancing concurrency and data consistency.
Understanding and effectively utilizing Mutex and RwLock helps ensure thread safety and prevent data races in multi-threaded applications. Keep exploring and practicing these synchronization primitives to build robust and efficient concurrent Rust programs!
Happy coding with Rust!
I hope this helps, you!!
More such articles:
https://www.youtube.com/@maheshwarligade
\==========================**=========================
If this article adds any value to you then please clap and comment.
Let’s connect on Stackoverflow, LinkedIn, & Twitter.