0

I'm new to learning about pthread_barriers 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;

I initialize the barrier with

  pthread_barrier_t bar;
  pthread_barrier_init( &bar, NULL, 2);

The thread code for A

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( &bar );
   if( max <= min ) return NULL;    // test to end trading rounds
   a[i] = min;                      // trade
}

The thread code for B

  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( &bar );
   if( max <= min ) return NULL;    // test to end trading rounds
   b[i] = max;                      // trade
 }

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:

Before

a: 1, 3, 5, 6, 7, 8, 9

b: 2, 4

After

a: 0, 0, 0, 0, 0, 0, 0

b: 2, 4

The values array

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
}

How the threads are made

rc = pthread_create( &threads[0], NULL, &minimize_a, (void *) &values[0] );
if( rc ){ printf( "** could not create m_a thread\n" ); exit( -1 ); }

rc = pthread_create( &threads[1], NULL, &maximize_b, (void *) &values[8] );
if( rc ){ printf( "** could not create m_b thread\n" ); exit( -1 ); }

Any tips, suggestions, or help please?

xCendwar
  • 1
  • 2

1 Answers1

0

You need additional synchronization for accessing the shared variables min and max.

After reaching the barrier, the minimize_a thread reads a value from min. Meanwhile the maximize_b thread is going to proceed to write a new value into min. There is nothing to guarantee that the value in min will be read before maximize_b replaces it with a new value. Try another pthread_barrier_wait at the end of each while loop.