pub struct ThreadPool { /* private fields */ }
Expand description
Threadpool will have a group of workers
who will be listening for jobs
.
Use the new
associated function to create a new threadpool
with size
number of workers
.
Use the execute
method to send
a job to the workers.
Implementations§
Source§impl ThreadPool
impl ThreadPool
Sourcepub fn new(size: usize, trace: bool) -> ThreadPool
pub fn new(size: usize, trace: bool) -> ThreadPool
This function will return a new ThreadPool
which will have size
number of workers(os threads)
.
Turn the trace
flag on to print the states of the workers.
§Example
use rahat3062_pool::ThreadPool; // Replace with your actual crate name
// Create a ThreadPool with 4 workers and tracing enabled
let pool = ThreadPool::new(4, true);
This example creates a ThreadPool
with 4 workers and enables tracing, which prints the states of the workers.
Sourcepub fn execute<F>(&self, f: F)
pub fn execute<F>(&self, f: F)
§Example
use rahat3062_pool::ThreadPool;
use std::sync::mpsc::channel;
use std::time::Duration;
let (sender, receiver) = channel();
let pool = ThreadPool::new(4, true);
for i in 0..10 {
let sender = sender.clone();
pool.execute(move || {
std::thread::sleep(Duration::from_millis(500));
sender.send(i + 1).unwrap();
});
}
// Explicitly drop the ThreadPool. This is not necessary, but it demonstrates that the jobs will continue to execute.
drop(pool);
// Close the channel to indicate that no more messages will be sent to make receiver.iter() unblocking.
drop(sender);
// Collect all the messages and check that we received the correct sum.
let result: i32 = receiver.iter().sum();
assert_eq!(result, 55); //((10*11)/2 = 55)
This example creates a ThreadPool
with 4 workers. It then creates 10 jobs that each sleep for a short time and then send a message on a channel. The ThreadPool
is dropped immediately after the jobs are submitted, but the jobs continue to execute. Later, the main thread collects all the messages and checks that it received the correct sum. This test exercises the ThreadPool
’s ability to run multiple jobs in parallel and shows that the jobs will continue to execute even if the ThreadPool
is dropped.