某些并行计算需要面临某些在计算进行前的某些单通瓶颈点,这种情况下,当然可以使用信号量的方式来进行处理,但是还存在着另外的一种处理方式是更加方便的,它就是:栅栏(在pthread库里面被定义成为类型 pthread_barrier_t),下面我们来看一段程序作为示例
1
#define _XOPEN_SOURCE 600
2
3
#include <pthread.h>
4
#include <stdlib,h>
5
#include <stdio.h>
6
7
#define ROWS 10000
8
#define COLS 10000
9
#define THREADS 10
10
11
double initial_matrix[ROWS][COLS];
12
double final_matrix[ROWS][COLS];
13
14
//Barrier variable
15
pthread_barrier_t barr
16
17
extern void DotProduct(int row, int col, double source[ROWS][COLS], double destination[ROWS][COLS]);
18
extern void determinant(double matrix[ROWS][COLS]);
19
20
void * entry_point(void * arg)
21

{
22
int rank = (int)arg;
23
int row;
24
for(row=rank*ROWS/THREADS; row < (rank+1)*THREADS;++row)
25
for(int col=0;col<COLS;++col)
26
DotProduct(row,col,initial_matrix,final_matrix);
27
28
//synchronization pointer
29
int rc = pthread_barrier_wait(&barr);
30
if(rc!=0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
31
{
32
printf("Could not wait on barrier\n");
33
exit(-1);
34
}
35
36
for(row=rank*ROWS/THREADS; row < (rank+1)*THREADS;++row)
37
for(int col=0;col<COLS;++col)
38
DotProduct(row,col,final_matrix,initial_matrix);
39
}
40
41
int main(int argc, char* argv[])
42

{
43
int i;
44
pthread_t thr[THREADS];
45
46
//Barrier initialization
47
if(pthread_barrierattr_init(&barr,NULL,THREADS))
48
{
49
50
printf("Could not create a barrier\n");
51
return -1;
52
}
53
54
for(i=0;i<THREADS;++i)
55
{
56
if(pthread_create(&thr[i],NULL,&entry_point, (void*)i))
57
{
58
59
printf("Could not create thread %d\n", i);
60
return -1;
61
}
62
}
63
64
for(i=0;i<THREADS;++i)
65
{
66
if(pthread_join(thr[i],NULL))
67
{
68
69
printf("Could not join thread %d\n", i);
70
return -1;
71
}
72
}
73
74
double det = determinant(initial_matrix);
75
printf("The determinant of M^4 = %f\n", det);
76
77
return 0;
78
79
}
这段程序产生出许多个线程,并且分配给每个线程计算矩阵乘法的一部分,然后每个线程使用这次计算的结果,继续进行下一步的计算:另一个矩阵的乘法
几点关于API的说明:
- barrier 变量必须在最开始声名为全局变量
- barrier 变量的初始化必须在main函数里进行初始化
- 在点上每一个线程都会等待它的对端完成工作
注意
在程序顶部的宏定义 _XOPEN_SOURCE 是非常重要的;如果没有这个变量,那么barrier类型就会在pthread.h中被屏蔽掉,这个定义必须在所有的头文件引用之前被定义出来
posted on 2010-10-02 23:47
sohu2000000 阅读(1122)
评论(0) 编辑 收藏 引用