【发布时间】:2014-04-20 12:38:23
【问题描述】:
我刚开始学习 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 ); }
请提供任何提示、建议或帮助?
【问题讨论】:
-
你能展示你如何启动线程以及如何声明数组吗?
-
是的,他们已被添加到问题中。
-
我假设
index_of_max对数组没有任何作用(即写入)?交换完成后,您可以非常小心地在每一步添加一些打印。
标签: c multithreading pthreads barrier