title: How can I wait for an unknown number of Rust threads to complete without using tracking handles?
body: <p>What are some good ways to adapt this <code>Barrier</code> example to handle two differences:</p>
  
  <ol>
  <li><p>the number of items is not known in advance (for example, in the case where splitting a large file into lines)</p></li>
  <li><p>without tracking thread handles (e.g. without using the <code>handles</code> vector in the example below). The motivation is that doing so adds additional overhead.</p></li>
  </ol>
  
  <p>Example code:</p>
  
  <pre><code>use std::sync::{Arc, Barrier};
  use std::thread;
  
  let mut handles = Vec::with_capacity(10);
  let barrier = Arc::new(Barrier::new(10));
  for _ in 0..10 {
      let c = barrier.clone();
      handles.push(thread::spawn(move|| {
          // do some work
          c.wait();
      }));
  }
  // Wait for other threads to finish.
  for handle in handles {
      handle.join().unwrap();
  }
  </code></pre>
  
  <p>Code snippet is adapted slightly from the <a href="https://doc.rust-lang.org/std/sync/struct.Barrier.html" rel="nofollow noreferrer"><code>Barrier</code> docs</a>.</p>
  
  <p>The first thing that crossed my mind would be (if possible) to mutate the inner value of the <code>Barrier</code>; however, the API does not provide mutable access to the <code>num_threads</code> property of the <code>Barrier</code> struct.</p>
  
  <p>Another idea would be to not use the <code>Barrier</code> and instead write custom  logic with <code>AtomicUsize</code>.</p>
  
  <p>I'm open to learning the most ergonomic / idiomatic ways to do this in Rust.</p>