Rust Multithreading with a Vector of different functions
To create a multithreaded program in Rust with a vector of different functions, you can use the std::thread
module. Here's an example:
use std::thread;
fn main() {
// Create a vector of functions
let functions: Vec<Box<dyn Fn() + Send + 'static>> = vec![
Box::new(|| {
println!("Thread 1");
}),
Box::new(|| {
println!("Thread 2");
}),
Box::new(|| {
println!("Thread 3");
}),
];
// Create a vector of threads
let threads: Vec<_> = functions
.into_iter()
.map(|f| {
thread::spawn(move || {
f();
})
})
.collect();
// Wait for all threads to finish
for thread in threads {
thread.join().expect("Thread panicked");
}
}
In this example, we define a vector functions
that contains three functions. Each function is wrapped in a Box<dyn Fn() + Send + 'static>
to make it suitable for storing in a vector. The Fn()
trait represents a closure that takes no arguments and returns nothing.
Next, we create a vector threads
by iterating over the functions
vector and spawning a new thread for each function. The move
keyword is used to transfer ownership of the function to the thread.
Finally, we wait for all the threads to finish by calling join()
on each thread.
When you run this program, you should see the output from each thread interleaved, indicating that they are running concurrently.