title: How to share limited resources between concurrently running tasks using Rust futures?
body: <p>I'm implementing a system that processes a certain kind of task asynchronously in Rust. In order to do this, I am using the <a href="https://crates.io/crates/futures" rel="nofollow noreferrer">futures</a> crate (the 0.2 beta version). </p>
  
  <p>Processing one of these tasks requires temporary but exclusive use of a certain type of resource, of which there are a fixed number of in the system. </p>
  
  <p>Keep in mind that this all takes place in a concurrent context: multiple threads may be trying to process a task at once. A simplified version of the interface I've been using is this:</p>
  
  <pre class="lang-rust prettyprint-override"><code>// 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(&amp;self, data: TaskData) -&gt; TaskFuture {
          TaskFuture { system: self }
      }
  }
  
  pub struct TaskFuture&lt;'a&gt; {
      system: &amp;'a System,
  }
  
  impl&lt;'a&gt; Future for TaskFuture&lt;'a&gt; {
      type Item = ?;
      type Error = ?;
      fn poll(&amp;mut self, cx: &amp;mut Context) -&gt; Result&lt;Async&lt;Self::Item&gt;, Self::Error&gt; {
          /* how can I implement this? */
      }
  }
  </code></pre>
  
  <p>As can be seen, I'm not quite sure what's the best way to implement such a system. </p>
  
  <p>My first thought would be to have the <code>System</code> hold several <code>Mutex&lt;Resource&gt;</code>s, and have <code>TaskFuture::poll</code> try to get one if available, and if not return <code>NotReady</code> (though I'm not sure how I would wake the future up later in that scenario). </p>
  
  <p>At any rate, I get the feeling that maybe I should avoid using the <code>std</code> synchronization primitives in a <code>futures</code>-based context unless absolutely necessary, so is there a more idiomatic <code>futures</code>-based solution to this? </p>