Advertisement
umuro

task_queue.rs

Apr 10th, 2023
1,342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.25 KB | Software | 0 0
  1. use std::sync::{Arc, Mutex};
  2. use std::thread;
  3. use std::time::Duration;
  4.  
  5. struct Task {
  6.     id: u64,
  7.     data: String,
  8. }
  9.  
  10. impl Task {
  11.     pub fn new(id: u64, data: String) -> Self {
  12.         Task { id, data }
  13.     }
  14. }
  15.  
  16. struct TaskQueue {
  17.     tasks: Mutex<Vec<Task>>,
  18.     stop_flag: Mutex<bool>,
  19. }
  20.  
  21. impl TaskQueue {
  22.     pub fn new() -> Self {
  23.         TaskQueue {
  24.             tasks: Mutex::new(Vec::new()),
  25.             stop_flag: Mutex::new(false),
  26.         }
  27.     }
  28.  
  29.     pub fn enqueue(&self, task: Task) {
  30.         let mut tasks = self.tasks.lock().unwrap();
  31.         tasks.push(task);
  32.     }
  33.  
  34.     pub fn dequeue(&self) -> Option<Task> {
  35.         let mut tasks = self.tasks.lock().unwrap();
  36.         tasks.pop()
  37.     }
  38.  
  39.     pub fn stop(&self) {
  40.         let mut stop_flag = self.stop_flag.lock().unwrap();
  41.         *stop_flag = true;
  42.     }
  43.  
  44.     pub fn should_stop(&self) -> bool {
  45.         let stop_flag = self.stop_flag.lock().unwrap();
  46.         *stop_flag
  47.     }
  48. }
  49.  
  50. fn main() {
  51.     let queue = Arc::new(TaskQueue::new());
  52.  
  53.     // Spawn 3 worker threads
  54.     let mut handles = vec![];
  55.  
  56.     for worker_id in 1..=3 {
  57.         let queue_clone = Arc::clone(&queue);
  58.         let handle = thread::spawn(move || {
  59.             while !queue_clone.should_stop() {
  60.                 if let Some(task) = queue_clone.dequeue() {
  61.                     println!("Worker {} is processing task {}: {}", worker_id, task.id, task.data);
  62.                     // Process the task (simulate with sleep)
  63.                     thread::sleep(Duration::from_millis(100));
  64.                 } else {
  65.                     // Sleep for a short duration if no task is available
  66.                     thread::sleep(Duration::from_millis(10));
  67.                 }
  68.             }
  69.             println!("Worker {} stopped.", worker_id);
  70.         });
  71.         handles.push(handle);
  72.     }
  73.  
  74.     // Add tasks to the queue
  75.     for i in 1..=10 {
  76.         queue.enqueue(Task::new(i, format!("Task {}", i)));
  77.         thread::sleep(Duration::from_millis(50));
  78.     }
  79.  
  80.     // Wait for a while before stopping the workers
  81.     thread::sleep(Duration::from_secs(5));
  82.     queue.stop();
  83.  
  84.     // Wait for all worker threads to finish
  85.     for handle in handles {
  86.         handle.join().unwrap();
  87.     }
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement