Created
February 14, 2024 19:50
-
-
Save RGGH/57dc74c8c69cb23b7419eb17713136c6 to your computer and use it in GitHub Desktop.
arc_mutex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cargo add colored ! | |
use std::sync::{Arc, Mutex}; | |
use std::thread; | |
use colored::Colorize; | |
fn main() { | |
// Create a shared counter wrapped in an Arc and Mutex | |
let counter = Arc::new(Mutex::new(1)); | |
// Create a vector to hold the thread handles | |
let mut handles = vec![]; | |
// Spawn 5 threads to increment the counter | |
for i in 0..5 { | |
let counter = Arc::clone(&counter); | |
let handle = thread::spawn(move || { | |
// Lock the mutex to access the shared counter | |
let mut num = counter.lock().unwrap(); | |
*num += 1; | |
// Colorize the thread's output based on its index | |
let colorized_text = match i { | |
0 => format!("{} incremented counter to {}", "red".red(), *num), | |
1 => format!("{} incremented counter to {}", "green".green(), *num), | |
2 => format!("{} incremented counter to {}", "yellow".yellow(), *num), | |
3 => format!("{} incremented counter to {}", "blue".blue(), *num), | |
4 => format!("{} incremented counter to {}", "magenta".magenta(), *num), | |
_ => format!("{} incremented counter to {}", "white".white(), *num), | |
}; | |
// Print the thread's colorized output | |
println!("{}", colorized_text); | |
}); | |
handles.push(handle); | |
} | |
// Wait for all threads to finish | |
for handle in handles { | |
handle.join().unwrap(); | |
} | |
// Print the final value of the counter | |
let final_value = counter.lock().unwrap(); | |
println!("Final Counter Value: {}", *final_value); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment