title: Threads on MacOS: libc++abi.dylib: terminating
body: <p>I have simple program to call threads what call threads. I'm sure that I'm missing something obviously. Belowe is code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;thread&gt;
  #include &lt;unistd.h&gt;
  
  using namespace std;
  
  vector&lt;thread&gt; threads;
  
  void Next(int amount) {
  for(int i = 0; i &lt; amount; i++) threads.push_back(thread(Next,amount-1));
  }
  
  int main(int argc, char **argv) {
  int amount = 2;
  
  for(int i = 0; i &lt; amount; i++) threads.push_back(thread(Next,amount-1));
  
  cout &lt;&lt; threads.size() &lt;&lt; endl;
  for (auto&amp; th : threads) {
      if (th.joinable()) {
          th.join();
      }
  }
  
  return 0;
  }
  </code></pre>
  
  <p>The output is different, for example:</p>
  
  <p>1.</p>
  
  <pre><code>2
  </code></pre>
  
  <p>2.</p>
  
  <pre><code>2
  libc++abi.dylib: terminating
  Abort trap: 6
  </code></pre>
  
  <p>3.</p>
  
  <pre><code>2
  libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: thread::join failed: No such process
  Abort trap: 6
  </code></pre>
  
  <p>I was searching any helpful information in internet and unfortunately didn't found anything.</p>
  
  <p>There is my second code what is working, but I wrote it good?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;thread&gt;
  #include &lt;unistd.h&gt;
  
  using namespace std;
  
  void Next(int amount) {
  vector&lt;thread&gt; threads;
  
  for(int i = 0; i &lt; amount; i++) threads.push_back(thread(Next,amount-1));
  
  cout &lt;&lt; threads.size() &lt;&lt; endl;
      for (auto&amp; th : threads) {
          if (th.joinable()) {
              th.join();
          }
      }
  }
  
  int main(int argc, char **argv) {
  int amount = 2;
  
  vector&lt;thread&gt; threads;
  
  for(int i = 0; i &lt; amount; i++) threads.push_back(thread(Next,amount-1));
  
  cout &lt;&lt; threads.size() &lt;&lt; endl;
  for (auto&amp; th : threads) {
      if (th.joinable()) {
          th.join();
      }
  }
  
  return 0;
  }
  </code></pre>
  
  <p>With mutex ( still problem ):</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;thread&gt;
  #include &lt;unistd.h&gt;
  #include &lt;mutex&gt;
  
  using namespace std;
  
  mutex mtx;
  vector &lt;thread&gt; threads;
  
  using namespace std;
  
  void Next(int amount) {
  for(int i = 0; i &lt; amount; i++) {
      mtx.lock();
      threads.push_back(thread(Next,amount-1));
      mtx.unlock();
  }
  }
  
  int main(int argc, char **argv) {
  int amount = 2;
  
  for(int i = 0; i &lt; amount; i++) {
      mtx.lock();
      threads.push_back(thread(Next,amount-1));
      mtx.unlock();
  }
  
  cout &lt;&lt; threads.size() &lt;&lt; endl;
  
  for (auto&amp; th : threads) {
      if (th.joinable()) {
          th.join();
      }
  }
  
  return 0;
  }
  </code></pre>