0

我遇到的问题是生命周期管理。我有一个注入器,我在工作线程之间共享它。我不得不使用Arc<>as&导致终生抱怨。本地队列不共享,所以不用担心。然后我们来到偷窃者。

从文档中,可以跨线程共享窃取。因此,4 个线程,每个线程都有一个 worker,每个线程都有 3 个窃取者。但是,我再次遇到了生命周期问题,这些问题似乎表明self线程何时产生。示例任务选择器表明窃取者可以表示为窃取者的切片,我最终得到的是对窃取者的引用切片。

也许我误解了文档,我应该使用Arc-style 引用计数来管理注入器和窃取器的生命周期。有人可以为我澄清一下吗?

这是一个包含 3 个线程的池的简化(排序)。我已经删除了围绕线程窃取器和注入器的生命周期管理,因为它们可能是或者Arc其他<'a>的。

// details on injector, worker and stealer can be found here:
// https://docs.rs/crossbeam/0.7.3/crossbeam/deque/index.html
struct ThreadData {
    injector: &deque::Injector::<Task>,     // common global queue
    task_q: deque::Worker::<Task>,          // local queue
    stealers: Vec<&deque::Stealer<Task>>    // stealers for other threads local queue
}
impl ThreadData {
    fn spawn(self) ->  Option<std::thread::JoinHandle<()>> {
        let thread = std::thread::spawn(move|| {
            find_task( &self.task_q, &self.injector, &self.stealers);
        });
        Some(thread)
    }
}
struct Worker {
    stealer: deque::Stealer<Task>,      // to be shared with other threads
    thread: Option<std::thread::JoinHandle<()>>
}

struct Factory {
    injector: deque::Injector::<Task> ,  // owner of the global queue
    workers: Vec<Worker>
}
impl Factory {
    fn new() -> Self {
        Self { injector: deque::Injector::<Task>::new(), workers: Vec::new() }
    }
    fn build_threadpool(mut self) {
        let mut t1 = ThreadData {
            injector: &self.injector,
            task_q: deque::Worker::<Task>::new_fifo(),
            stealers: Vec::new(),
        };
        let w1 = Worker {stealer: t1.task_q.stealer(), thread: None };

        let t2 = ThreadData {
            injector: &self.injector,
            task_q: deque::Worker::<Task>::new_fifo(),
            stealers: Vec::new(),
        };
        let w2 = Worker {stealer: t2.task_q.stealer(), thread: None};

        let t3 = ThreadData {
            injector: &self.injector,
            task_q: deque::Worker::<Task>::new_fifo(),
            stealers: Vec::new(),
        };
        let w3 = Worker {stealer: t3.task_q.stealer(), thread: None };

        t1.stealers.push(&w2.stealer);
        t1.stealers.push(&w3.stealer);

        t2.stealers.push(&w1.stealer);
        t2.stealers.push(&w3.stealer);

        t3.stealers.push(&w1.stealer);
        t3.stealers.push(&w2.stealer);

        // launch threads and save workers
        w1.thread = t1.spawn();
        w2.thread = t2.spawn();
        w3.thread = t3.spawn();

        self.workers.push(w1);
        self.workers.push(w2);
        self.workers.push(w3);
    }

}
4

0 回答 0