0

我刚开始学习pthread_barriers它们以及它们是如何工作的。基本上我有两个数组和两个线程,一个线程找到数组 A 的最大值,另一个找到数组 B 的最小值并将它们存储在全局变量中。他们需要在进行交易之前进行同步(A 的最大值传递给 B,B 的最小值传递给 A),这样数组 B 的所有值都比 A 高——如果你愿意的话,几乎就像一个排序问题。我不断得到非常不正确的结果,我确信我错过了一些简单的东西;

我用

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

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
}

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
 }

如果我的理解是正确的,一旦两个线程都命中 pthread_barrier_wait,它们将成功同步并可以继续,对吗?我总是得到如下疯狂的结果:

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

b: 2, 4

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

b: 2, 4

值数组

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
}

螺纹是如何制作的

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 ); }

请问有什么提示、建议或帮助吗?

4

1 回答 1

0

您需要额外的同步来访问共享变量 min 和 max。

到达屏障后,minimize_a 线程从 min 中读取一个值。同时,maximize_b 线程将继续将新值写入 min。没有什么可以保证在将 min 中的值替换为新值之前会读取 min 中的值。在每个 while 循环结束时尝试另一个 pthread_barrier_wait。

于 2014-03-17T05:12:03.533 回答