You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lib.rs 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. use std::thread;
  2. use std::sync::{mpsc, Mutex, Arc};
  3. pub struct ThreadPool{
  4. workers: Vec<Worker>,
  5. sender: mpsc::Sender<Job>,
  6. }
  7. type Job = Box<dyn FnOnce() + Send + 'static>;
  8. impl ThreadPool {
  9. pub fn new(size: usize) -> ThreadPool {
  10. assert!(size > 0);
  11. let (sender, receiver) = mpsc::channel();
  12. let receiver = Arc::new(Mutex::new(receiver));
  13. let mut workers = Vec::with_capacity(size);
  14. for id in 0..size {
  15. workers.push(Worker::new(id, Arc::clone(&receiver)));
  16. }
  17. ThreadPool {
  18. workers,
  19. sender,
  20. }
  21. }
  22. pub fn execute<F>(&self, f: F)
  23. where F: FnOnce() + Send + 'static
  24. {
  25. let job = Box::new(f);
  26. self.sender.send(job).unwrap();
  27. }
  28. // pub fn spawn<F, T>(f: F) -> JoinHandle<T>
  29. // where
  30. // F: FnOnce() -> T + Send + 'static,
  31. // T: Send + 'static
  32. // {
  33. // }
  34. }
  35. impl Drop for ThreadPool {
  36. fn drop(&mut self) {
  37. for worker in &mut self.workers {
  38. println!("Shutting down worker {}", worker.id);
  39. worker.thread.join().unwrap();
  40. }
  41. }
  42. }
  43. struct Worker {
  44. id: usize,
  45. thread: thread::JoinHandle<()>,
  46. }
  47. impl Worker {
  48. fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
  49. let thread = thread::spawn(move || {
  50. loop {
  51. let job = receiver.lock().unwrap().recv().unwrap();
  52. println!("Worker {} got a job, executing.", id);
  53. job();
  54. }
  55. });
  56. Worker {
  57. id,
  58. thread,
  59. }
  60. }
  61. }