Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::sync::{Arc, Mutex};
- use std::thread;
- use std::time::Duration;
- struct Task {
- id: u64,
- data: String,
- }
- impl Task {
- pub fn new(id: u64, data: String) -> Self {
- Task { id, data }
- }
- }
- struct TaskQueue {
- tasks: Mutex<Vec<Task>>,
- stop_flag: Mutex<bool>,
- }
- impl TaskQueue {
- pub fn new() -> Self {
- TaskQueue {
- tasks: Mutex::new(Vec::new()),
- stop_flag: Mutex::new(false),
- }
- }
- pub fn enqueue(&self, task: Task) {
- let mut tasks = self.tasks.lock().unwrap();
- tasks.push(task);
- }
- pub fn dequeue(&self) -> Option<Task> {
- let mut tasks = self.tasks.lock().unwrap();
- tasks.pop()
- }
- pub fn stop(&self) {
- let mut stop_flag = self.stop_flag.lock().unwrap();
- *stop_flag = true;
- }
- pub fn should_stop(&self) -> bool {
- let stop_flag = self.stop_flag.lock().unwrap();
- *stop_flag
- }
- }
- fn main() {
- let queue = Arc::new(TaskQueue::new());
- // Spawn 3 worker threads
- let mut handles = vec![];
- for worker_id in 1..=3 {
- let queue_clone = Arc::clone(&queue);
- let handle = thread::spawn(move || {
- while !queue_clone.should_stop() {
- if let Some(task) = queue_clone.dequeue() {
- println!("Worker {} is processing task {}: {}", worker_id, task.id, task.data);
- // Process the task (simulate with sleep)
- thread::sleep(Duration::from_millis(100));
- } else {
- // Sleep for a short duration if no task is available
- thread::sleep(Duration::from_millis(10));
- }
- }
- println!("Worker {} stopped.", worker_id);
- });
- handles.push(handle);
- }
- // Add tasks to the queue
- for i in 1..=10 {
- queue.enqueue(Task::new(i, format!("Task {}", i)));
- thread::sleep(Duration::from_millis(50));
- }
- // Wait for a while before stopping the workers
- thread::sleep(Duration::from_secs(5));
- queue.stop();
- // Wait for all worker threads to finish
- for handle in handles {
- handle.join().unwrap();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement