I'am writing a ThreadPool using a VecDeque and a Condvar for waiting. However, I don't get any speed increase when increasing the number of threads. Printing the IDs of the threads which are processing the data reveals that mostly one thread is working and the others seem not to be able to get to work.
This is a minimal example which shows the same behaviour (at least on my machine).
Changing the sleep duration seems to have an impact in this example. However, this of course only simulates other work.
Can someone please explain
1. if I'am doing something fundamentally wrong or
2. how to better distribute the work across the threads.
use std::sync::{Arc, Mutex, Condvar};
use std::thread;
use std::collections::VecDeque;
use std::time::Duration;
fn main() {
let queue = Arc::new((Mutex::new(VecDeque::new()), Condvar::new()));
let threads = (0..4).map(|i| {
let queue2 = queue.clone();
thread::spawn(move || {
loop {
let (ref queue, ref condvar) = *queue2;
let mut queue = queue.lock().unwrap();
while queue.len() == 0 {
queue = condvar.wait(queue).unwrap();
}
if let Some(value) = queue.pop_front() {
thread::sleep(Duration::from_millis(40));
println!("[{}] processing {}", i, value);
}
}
})
}).collect::<Vec<_>>();
for i in 0..100 {
let (ref queue, ref condvar) = *queue;
let mut queue = queue.lock().unwrap();
queue.push_back(i);
condvar.notify_all();
}
for thread in threads {
thread.join().expect("Couldn't join.");
}
}