Skip to content

Instantly share code, notes, and snippets.

@cbwar
Last active February 9, 2025 12:11
Show Gist options
  • Save cbwar/b62882a889c9e2bea26f796f4f1c6e0c to your computer and use it in GitHub Desktop.
Save cbwar/b62882a889c9e2bea26f796f4f1c6e0c to your computer and use it in GitHub Desktop.
Example of using a Mutex to share data between threads
#![allow(unused)]
use std::{collections::HashMap, sync::{Arc, Mutex}};
use rand::Rng;
#[derive(Debug)]
struct UserData {
name: String,
age: u32,
}
impl UserData {
fn new(name: String, age: u32) -> UserData {
UserData { name, age }
}
}
const FIRST_NAMES: &[&str] = &["Alex", "Olivia", "Liam", "Sophia", "Noah", "Emma", "Ethan", "Ava", "Caden", "Mia"];
fn get_random_firstname() -> &'static str {
let index = rand::rng().random_range(1..FIRST_NAMES.len());
FIRST_NAMES[index]
}
/// Example of using a Mutex to share data between threads
/// The data is a HashMap with an integer key and a UserData value
/// Each thread will insert a new UserData into the HashMap
/// The main thread will wait for all threads to finish and then print the HashMap
fn main() {
let data : Arc<Mutex<HashMap<i32,UserData>>>= Arc::new(Mutex::new(HashMap::new()));
println!("Memory usage of data: {:?}", std::mem::size_of_val(&data));
let mut threads: HashMap<i32, std::thread::JoinHandle<()>> = HashMap::new();
for i in 0..10 {
// Clone the data to move it into the thread
let data = data.clone();
let thread = std::thread::spawn(move || {
println!("#{} Thread starting...", i);
// Sleep between 10 and 5000 ms
std::thread::sleep(std::time::Duration::from_millis(rand::rng().random_range(10..5000)));
let age = rand::rng().random_range(20..80);
let firstname= get_random_firstname().to_string();
let user = UserData::new(firstname.to_string(), age);
println!("#{} Data generated, waiting lock...", i);
data.lock().unwrap().insert(i, user);
println!("#{} Thread ended.", i);
});
threads.insert(i, thread);
}
println!("All threads created");
// Wait for all threads to finish
for (i, thread) in threads {
thread.join().unwrap();
}
let data = data.lock().unwrap();
assert_eq!(data.len(), 10);
println!("User data: {:?}", data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment