C pthread_barrier synchronization issues <p>I'm new to learning about <code>pthread_barriers</code> and how they work. Basically I have two arrays and two threads, one thread finds the max of array A and another finds the min of array B and stores them in global variables. They need to synchronize right before they make a trade (the max of A is passed to B and the min of B is passed to A) so that array B has all higher values than A - almost like a sorting problem, if you will. I keep getting wildly incorrect results and I'm sure I'm missing something simple;</p> <p><strong>I initialize the barrier with</strong></p> <pre><code> pthread_barrier_t bar; pthread_barrier_init( &amp;bar, NULL, 2); </code></pre> <p><strong>The thread code for A</strong></p> <pre><code>void *minimize_a( void *arg ) int i; int size_a = *((int *) arg); // first location is count of values int *a = ((int *) arg) + 1; // a[] will be array of values while(1){ i = index_of_max( a, size_a ); max = a[i]; // offer max for trade pthread_barrier_wait( &amp;bar ); if( max &lt;= min ) return NULL; // test to end trading rounds a[i] = min; // trade } </code></pre> <p><strong>The thread code for B</strong></p> <pre><code> void *maximize_b( void *arg ) int i; int size_b = *((int *) arg); // first location is count of values int *b = ((int *) arg) + 1; // b[] will be array of values while(1){ i = index_of_min( b, size_b ); min = b[i]; // new min found pthread_barrier_wait( &amp;bar ); if( max &lt;= min ) return NULL; // test to end trading rounds b[i] = max; // trade } </code></pre> <p>If I'm correct in understanding, once both threads hit pthread_barrier_wait, they will have successfuly synchronized and can keep continuing, correct? I always get crazy results like the following:</p> <p><strong>Before</strong></p> <p><code>a: 1, 3, 5, 6, 7, 8, 9</code></p> <p><code>b: 2, 4</code></p> <p><strong>After</strong></p> <p><code>a: 0, 0, 0, 0, 0, 0, 0</code></p> <p><code>b: 2, 4</code></p> <p>The values array</p> <pre><code>int values[] = { // format of each set of values: // count of value n, then n integer values 7, 1,3,5,6,7,8,9, // this set of values starts at index 0 2, 2,4, // starts at index 8 5, 1,3,5,7,9, // starts at index 11 5, 0,2,4,6,8 // starts at index 17 } </code></pre> <p>How the threads are made</p> <pre><code>rc = pthread_create( &amp;threads[0], NULL, &amp;minimize_a, (void *) &amp;values[0] ); if( rc ){ printf( "** could not create m_a thread\n" ); exit( -1 ); } rc = pthread_create( &amp;threads[1], NULL, &amp;maximize_b, (void *) &amp;values[8] ); if( rc ){ printf( "** could not create m_b thread\n" ); exit( -1 ); } </code></pre> <p>Any tips, suggestions, or help please?</p>