Open fan-tastic-z opened 2 months ago
现在pdf 中的代码 感觉不是特别好理解,更改为如下代码是不是会更好点:
use std::{ sync::{Arc, Mutex}, thread, }; use crossbeam::deque::{Injector, Steal, Worker}; fn main() { let injector = Arc::new(Injector::new()); let worker1 = Arc::new(Mutex::new(Worker::<i32>::new_fifo())); let worker2 = Arc::new(Mutex::new(Worker::<i32>::new_fifo())); for i in 0..10 { injector.push(i); } let worker1_clone = Arc::clone(&worker1); let injector_clone1 = Arc::clone(&injector); let handle1 = thread::spawn(move || loop { let worker1 = worker1_clone.lock().unwrap(); if let Some(task) = worker1.pop() { println!("worker1 executing task: {}", task); } else { // 窃取一批任务,将它们推送到 worker1 中 match injector_clone1.steal_batch_and_pop(&worker1) { Steal::Empty => break, Steal::Success(task) => println!("worker1 stole task: {} from injector", task), Steal::Retry => continue, } } }); let worker2_clone = Arc::clone(&worker2); let injector_clone2 = Arc::clone(&injector); let handle2 = thread::spawn(move || loop { let worker2 = worker2_clone.lock().unwrap(); if let Some(task) = worker2.pop() { println!("worker2 executing task: {}", task); } else { // 窃取一批任务,将它们推送到 worker1 中 match injector_clone2.steal() { Steal::Empty => break, Steal::Success(task) => println!("worker2 stole task: {} from worker1", task), Steal::Retry => continue, } } }); let injector_clone3 = Arc::clone(&injector); let worker1_clone2 = Arc::clone(&worker1); let handle3 = thread::spawn(move || loop { // 窃取一批任务,将它们推送到 worker1 中 match injector_clone3.steal_batch_and_pop(&worker1_clone2.lock().unwrap()) { Steal::Empty => break, Steal::Success(task) => println!("worker1 stole task: {} from injector", task), Steal::Retry => continue, } }); handle1.join().unwrap(); handle2.join().unwrap(); handle3.join().unwrap(); }
请标注多少页的代码,否则不容易查找修改
补充pdf 页数:157-158 关于 并发工作窃取双向队列的示例代码
现在pdf 中的代码 感觉不是特别好理解,更改为如下代码是不是会更好点: