拥有所有权和借用的麻烦,以及跨多个线程共享实例

时间:2015-09-05 22:23:42

标签: multithreading rust

我正试图通过名为workers的玩具项目来学习Rust。我正在尝试task.perform() inside a thread pool

问题:

    Compiling workers v0.1.0 (file:///Users/endel/Projects/rust/workers)
src/lib.rs:45:21: 45:32 error: cannot infer an appropriate lifetime for autoref due to conflicting requirements
src/lib.rs:45     let next = self.next_task();
                                  ^~~~~~~~~~~
src/lib.rs:45:16: 45:20 note: first, the lifetime cannot outlive the expression at 45:15...
src/lib.rs:45     let next = self.next_task();
                             ^~~~
src/lib.rs:45:16: 45:20 note: ...so that auto-reference is valid at the time of borrow
src/lib.rs:45     let next = self.next_task();
                             ^~~~
src/lib.rs:45:16: 45:32 note: but, the lifetime must be valid for the method call at 45:15...
src/lib.rs:45     let next = self.next_task();
                             ^~~~~~~~~~~~~~~~
src/lib.rs:45:16: 45:20 note: ...so that method receiver is valid for the method call
src/lib.rs:45     let next = self.next_task();
                             ^~~~
error: aborting due to previous error

我已经在#rust IRC频道中寻求帮助,他们建议使用Box<Task>(拥有)而不是&Box<Task>(借用),以便在{{1}期间复制任务我猜想。声明。

这是一个可行的解决方案吗?还有别的吗?我已尝试将move || {} impl方法从Worker更改为&self,但其他问题开始出现,我无法为我的self获取Box<Task> {1}}方法。

以下是playgound中展示问题的简化版本。

1 个答案:

答案 0 :(得分:0)

我在#rust IRC频道和tomaka answered me上询问过这个问题。

基本上:

  • &Box<Task>更改为Box<Task>
  • get_task_by_name现在从Vec
  • 中删除了一个元素
  • Vec现在位于Mutex中,以便您可以对其进行修改