pbrt_r3/core/integrator/
mt.rs

1use std::sync::Arc;
2use std::sync::Mutex;
3use std::sync::RwLock;
4
5pub trait ThreadContainer: Send + Sync {
6    fn func(&self);
7}
8
9pub struct AContainer {}
10impl ThreadContainer for AContainer {
11    fn func(&self) {
12        let _idx = rayon::current_thread_index().unwrap();
13        //println!("{}:AContainer::func",idx);
14    }
15}
16
17pub struct ThreadExecutor {
18    pub container: Arc<Mutex<dyn ThreadContainer>>, //Arc<Mutex<dyn ThreadContainer>>,
19    //pub c1: Box<dyn ThreadContainer>,
20    //pub c2: Arc<RefCell<dyn ThreadContainer>>,
21    pub c3: Arc<RwLock<dyn ThreadContainer>>,
22}
23
24impl ThreadExecutor {
25    pub fn new() -> Self {
26        ThreadExecutor {
27            container: Arc::new(Mutex::new(AContainer {})), //Arc::new(Mutex::new(AContainer{})),
28            //c1: Box::new(AContainer{}),
29            //c2: Arc::new(RwLock::new(AContainer{}))
30            c3: Arc::new(RwLock::new(AContainer {})),
31        }
32    }
33    pub fn test_task(&self, _x: i32, _y: i32) {
34        {
35            let c3 = self.c3.read().unwrap();
36            c3.func();
37        }
38        {
39            let _weak = Arc::downgrade(&self.c3);
40            //weak.
41        }
42
43        {
44            let c = self.container.lock().unwrap();
45            c.func();
46        }
47
48        //println!("{}, {}", x, y);
49        //self.container.borrow().func();
50    }
51    pub fn execute(&self) {
52        let inputs = Arc::new(Mutex::new(Vec::new()));
53        {
54            let mut queue = inputs.lock().unwrap();
55            for y in 0..100 {
56                for x in 0..100 {
57                    queue.push((x, y));
58                }
59            }
60        }
61        {
62            let pool = rayon::ThreadPoolBuilder::new().build().unwrap();
63            //println!("{}", pool.current_num_threads());
64            loop {
65                let mut queue = inputs.lock().unwrap();
66                if queue.is_empty() {
67                    break;
68                } else {
69                    if let Some((x, y)) = queue.pop() {
70                        pool.install(|| {
71                            self.test_task(x, y);
72                        });
73                    }
74                }
75            }
76        }
77    }
78}