title: Why does pthread_join not close an array of threads properly in this example?
body: <p>I am trying to teach myself pthreads threading. I have the following source, which compiles and runs properly:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  
  #define PTHREAD_COUNT 10
  #define FREQ 5
  
  void *thread_function(void *arg) {
    int *incoming = (int *)arg;
    int freqIdx;
  
    for (freqIdx = 0; freqIdx &lt; FREQ; freqIdx++)
      fprintf(stdout, "Hello, world (thread %d)\n", *incoming);
  
    return NULL;
  }
  
  int main(int argc, char **argv) {
    pthread_t thread_IDs[PTHREAD_COUNT];
    void *exit_status;
    int threadIdx;
  
    for (threadIdx = 0; threadIdx &lt; PTHREAD_COUNT; threadIdx++) {
      pthread_create(&amp;thread_IDs[threadIdx], NULL, thread_function, &amp;threadIdx);
      pthread_join(thread_IDs[threadIdx], &amp;exit_status);
    }
  
    return 0;
  }
  </code></pre>
  
  <p>I get the following result:</p>
  
  <pre><code>Hello, world (thread 0)
  Hello, world (thread 0)
  Hello, world (thread 0)
  Hello, world (thread 0)
  Hello, world (thread 0)
  Hello, world (thread 1)
  ...
  Hello, world (thread 9)
  </code></pre>
  
  <p>If I <code>pthread_create</code> an array of <code>pthread_t</code> types over a loop, and then <code>pthread_join</code> in a separate loop, then things fail:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  
  #define PTHREAD_COUNT 10
  #define FREQ 5
  
  void *thread_function(void *arg) {
    int *incoming = (int *)arg;
    int freqIdx;
  
    for (freqIdx = 0; freqIdx &lt; FREQ; freqIdx++)
      fprintf(stdout, "Hello, world (thread %d)\n", *incoming);
  
    return NULL;
  }
  
  int main(int argc, char **argv) {
    pthread_t thread_IDs[PTHREAD_COUNT];
    void *exit_status;
    int threadIdx;
  
    /* here I split the thread _create and _join steps into separate loops */
  
    for (threadIdx = 0; threadIdx &lt; PTHREAD_COUNT; threadIdx++)
      pthread_create(&amp;thread_IDs[threadIdx], NULL, thread_function, &amp;threadIdx);
  
    for (threadIdx = 0; threadIdx &lt; PTHREAD_COUNT; threadIdx++)
      pthread_join(thread_IDs[threadIdx], &amp;exit_status);
  
    return 0;
  }
  </code></pre>
  
  <p>The output from this is quite wrong. Instead of getting five <code>fprintf</code> statements from each thread, I get one or two from, say, thread 2 and 3, and about 20 to 25 <code>Hello, world</code> statements from thread 0.</p>
  
  <p>Why does this fail?</p>