Day 29: Practice writing concurrent code in Rust.

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...
Day 29 is a great opportunity to practice writing concurrent code in Rust. Let's dive into a few exercises involving threads, Mutex, and RwLock to reinforce your understanding of concurrent programming in Rust.
Write a program using Mutex to implement a counter shared among multiple threads. Each thread should increment the counter several times.
use std::sync::{Mutex, Arc};
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 || {
for _ in 0..100 {
let mut num = counter.lock().unwrap();
*num += 1;
}
});
handles.push(handle);
}
for handle in handles {
handle.join().expect("Thread panicked!");
}
println!("Final Counter: {:?}", *counter.lock().unwrap());
}
Create a program utilizing RwLock to manage shared data access. Multiple threads should read the data simultaneously, while one thread writes to it.
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());
}
Implement a simple producer-consumer problem using channels to pass data between threads.
use std::sync::mpsc;
use std::thread;
fn main() {
let (sender, receiver) = mpsc::channel();
let producer = thread::spawn(move || {
for i in 1..=5 {
sender.send(i).unwrap();
println!("Produced: {}", i);
}
});
let consumer = thread::spawn(move || {
for _ in 1..=5 {
let received = receiver.recv().unwrap();
println!("Consumed: {}", received);
}
});
producer.join().expect("Producer panicked!");
consumer.join().expect("Consumer panicked!");
}
Feel free to modify these exercises or create new ones to further enhance your understanding of concurrent programming in Rust. Practicing with threads, Mutex, RwLock, and channels will strengthen your ability to write safe and efficient concurrent code in Rust!
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.