如何使用Rust期货在同时运行的任务之间共享有限的资源?

时间:2018-04-02 03:44:17

标签: concurrency rust future

我实现了一个在Rust中异步处理某种任务的系统。为了做到这一点,我使用的是futures crate(0.2 beta版)。处理这些任务之一需要临时但独占使用某种类型的资源,其中系统中有固定数量的资源。

请记住,这一切都发生在并发上下文中:多个线程可能正在尝试一次处理任务。我正在使用的界面的简化版本是:

// A fixed number of these are held by the System, and a TaskFuture needs one to complete.
pub struct Resource { ... }

pub struct System { /* how should the system hold Resources? */ }
impl System {
    pub fn queue_task(&self, data: TaskData) -> TaskFuture {
       TaskFuture { system: self }
    }
}

pub struct TaskFuture<'a> { system: &'a System, ... }

impl<'a> Future for TaskFuture<'a> {
    type Item = ...;
    type Error = ...;
    fn poll(&mut self, cx: &mut Context) -> Result<Async<Self::Item>, Self::Error> {
        /* how can I implement this? */
    }
}

可以看出,我不太清楚实现这样一个系统的最佳方法是什么。

我的第一个想法是让System持有多个Mutex<Resource>,让TaskFuture::poll尝试获得一个{}}如果可用,如果不能返回NotReady(尽管我不确定在那种情况下我将如何唤醒未来。)无论如何,我觉得除非绝对必要,否则我应该避免在基于std的上下文中使用futures同步原语,因此是否存在更基于惯用futures的解决方案这个?

0 个答案:

没有答案
相关问题