title: Barriers for thread syncing
body: <p>I'm creating n threads &amp; then starting then execution after a barrier breakdown.</p>
  
  <p>In global data space:</p>
  
  <pre><code>int bkdown = 0;
  </code></pre>
  
  <p>In main():</p>
  
  <pre><code>pthread_barrier_init(&amp;bar,NULL,n);
  
  for(i=0;i&lt;n;i++)
  {
  pthread_create(&amp;threadIdArray[i],NULL,runner,NULL);
  if(i==n-2)printf("breakdown imminent!\n");
  if(i==n-1)printf("breakdown already occurred!\n");
  }
  </code></pre>
  
  <p>In thread runner function:</p>
  
  <pre><code>void *runner(void *param)
  {
   pthread_barrier_wait(&amp;bar);
  
   if(bkdown==0){bkdown=1;printf("barrier broken down!\n");}
  
          ...
  
   pthread_exit(NULL);
  }
  </code></pre>
  
  <p><strong>Expected order:</strong></p>
  
  <pre><code>breakdown imminent!
  barrier broken down!
  breakdown already occurred!
  </code></pre>
  
  <p><strong>Actual order:</strong> <em>(tested repeatedly)</em></p>
  
  <pre><code>breakdown imminent!
  breakdown already occurred!
  barrier broken down!!
  </code></pre>
  
  <p>Could someone explain why the I am not getting the <code>"broken down"</code> message before the <code>"already occurred"</code> message?</p>