title: Can I signal multiple threads simultaneously with pthread_cond_wait(,)?
body: <p>I am writing various code snippets and see what happens. The code below was intended to delay all threads until all reached a certain point in the code and then make each print a distinctive number. Since the threads all do that, the numbers should occur in a random order.</p>
  
  <p>My current problem is that I keep they threads busy waiting. If the number of threads gets big, the program slows down significantly. </p>
  
  <p>I would like to change that by using signals, I found <code>pthread_cond_wait()</code> for that, however I don't see how one would use that to signal all threads that they would please wake up.</p>
  
  <pre><code>#include &lt;pthread.h&gt; 
  #include &lt;stdio.h&gt; 
  #include &lt;unistd.h&gt; 
  
  #define threads 10
  
  int counter=0; 
  pthread_mutex_t lock; 
  
  void handler(void *v) {
  
      pthread_mutex_lock(&amp;lock);  
      counter++;
      printf("%d\n", counter); 
      pthread_mutex_unlock(&amp;lock);   
      while(counter != threads); // busy waiting
  
      printf("I am first! %d\n", v); 
  
  }
  
  
  int main() {
  
      pthread_t t[threads]; 
      for(int i =0; i &lt; threads; i++) {       
      pthread_create(&amp;t[i], NULL, handler, (void*) i); 
      }
      for(int i =0; i &lt; threads; i++) {       
      pthread_join(t[i], NULL); 
      }
  
      return 0; 
  }
  </code></pre>
  
  <p>EDIT: I changed the code to the following, however, it still does not work :/</p>
  
  <pre><code>pthread_mutex_t lock; 
  pthread_cond_t cv; 
  
  void handler(void *v) {
      pthread_mutex_lock(&amp;lock);
      pthread_cond_wait(&amp;cv, &amp;lock);
      printf("I am first! %d\n", v); 
      pthread_mutex_unlock(&amp;lock);
  }
  
  
  int main() {
      pthread_t t[threads]; 
      for(int i =0; i &lt; threads; i++) 
          pthread_create(&amp;t[i], NULL, handler, (void*) i); 
          sleep(2); 
      pthread_cond_signal(&amp;cv); 
      for(int i =0; i &lt; threads; i++) 
          pthread_join(t[i], NULL); 
      return 0; 
  }
  </code></pre>