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.

thread_pool.rs 3.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. use std::{
  2. sync::{mpsc, Arc, Mutex},
  3. thread
  4. };
  5. pub struct ThreadPool {
  6. workers: Vec<Worker>,
  7. sender: Option<mpsc::Sender<Job>>,
  8. }
  9. // Box: pointer for heap allocation (smart pointer); dyn: unknown type to compile time
  10. type Job = Box<dyn FnOnce() + Send + 'static>;
  11. impl ThreadPool {
  12. /// Create a new ThreadPool.
  13. ///
  14. /// The size is the number of threads in the pool.
  15. ///
  16. /// # Panics
  17. ///
  18. /// The `new` function will panic if the size is zero.
  19. pub fn new(size: usize) -> ThreadPool {
  20. assert!(size > 0);
  21. // create asynchronous channel with sender/receiver pair (for jobs!)
  22. let (sender, receiver) = mpsc::channel();
  23. // protect receiver with thread-safe shared (Arc) mutex to avoid multiple access
  24. let receiver = Arc::new(Mutex::new(receiver));
  25. // pre(!)allocate space for workers
  26. let mut workers = Vec::with_capacity(size);
  27. // initialize all workers...
  28. for id in 0..size {
  29. // create worker with unique id and pointer to the shared mutex
  30. workers.push(Worker::new(id, Arc::clone(&receiver)));
  31. }
  32. // set thread pool variables
  33. ThreadPool {
  34. workers,
  35. // Some --> enum variant (Option): indicates that sender may not exist (=be null)
  36. sender: Some(sender),
  37. }
  38. }
  39. pub fn execute<F>(&self, f: F)
  40. where
  41. // FnOnce() --> only callable once; Send --> transfer to another thread; 'static --> lifetime
  42. F: FnOnce() + Send + 'static,
  43. {
  44. let job = Box::new(f);
  45. // commit job to sender object --> pass to threads for execution
  46. self.sender.as_ref().unwrap().send(job).unwrap();
  47. }
  48. }
  49. impl Drop for ThreadPool {
  50. fn drop(&mut self) {
  51. // drop sender first
  52. drop(self.sender.take());
  53. // then drop workers
  54. for worker in &mut self.workers {
  55. println!("Shutting down worker {}", worker.id);
  56. // join worker thread
  57. if let Some(thread) = worker.thread.take() {
  58. thread.join().unwrap();
  59. }
  60. }
  61. }
  62. }
  63. struct Worker {
  64. id: usize,
  65. thread: Option<thread::JoinHandle<()>>,
  66. }
  67. impl Worker {
  68. /// Create a new Worker..
  69. ///
  70. /// The id is a unique identifier.
  71. /// The receiver is a shared pointer to a receiver protected by Mutex.
  72. fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
  73. // spawn thread and enter infinite loop
  74. let thread = thread::spawn(move || loop {
  75. // lock mutex and wait for job
  76. let message = receiver.lock().unwrap().recv();
  77. match message {
  78. // normal operation --> execute job
  79. Ok(job) => {
  80. println!("Worker {id} got a job; executing.");
  81. job();
  82. }
  83. // exit gracefully when pool is closed --> recv will return error then
  84. Err(_) => {
  85. println!("Worker {id} disconnected; shutting down.");
  86. break;
  87. }
  88. }
  89. });
  90. Worker {
  91. id,
  92. thread: Some(thread),
  93. }
  94. }
  95. }