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.
Exercise 1: Mutex-based Counter
Write a program using Mutex to implement a counter shared among multiple threads. Each thread should increment the counter several times.
Example Solution:
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());
}
Exercise 2: Read-Write Lock Usage
Create a program utilizing RwLock to manage shared data access. Multiple threads should read the data simultaneously, while one thread writes to it.
Example Solution:
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());
}
Exercise 3: Producer-Consumer Problem
Implement a simple producer-consumer problem using channels to pass data between threads.
Example Solution:
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.