- 論壇徽章:
- 0
|
某些并行計(jì)算需要面臨某些在計(jì)算進(jìn)行前的某些單通瓶頸點(diǎn),這種情況下,當(dāng)然可以使用信號(hào)量的方式來進(jìn)行處理,但是還存在著另外的一種處理方式是更加方便的,它就是:柵欄(在pthread庫(kù)里面被定義成為類型 pthread_barrier_t),下面我們來看一段程序作為示例- #define _XOPEN_SOURCE 600
- #include <pthread.h>
- #include <stdlib,h>
- #include <stdio.h>
- #define ROWS 10000
- #define COLS 10000
- #define THREADS 10
- double initial_matrix[ROWS][COLS];
- double final_matrix[ROWS][COLS];
- //Barrier variable
- pthread_barrier_t barr
- extern void DotProduct(int row, int col, double source[ROWS][COLS], double destination[ROWS][COLS]);
- extern void determinant(double matrix[ROWS][COLS]);
- void * entry_point(void * arg)
- {
- int rank = (int)arg;
- int row;
- for(row=rank*ROWS/THREADS; row < (rank+1)*THREADS;++row)
- for(int col=0;col<COLS;++col)
- DotProduct(row,col,initial_matrix,final_matrix);
- //synchronization pointer
- int rc = pthread_barrier_wait(&barr);
- if(rc!=0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
- {
- printf("Could not wait on barrier\n");
- exit(-1);
- }
- for(row=rank*ROWS/THREADS; row < (rank+1)*THREADS;++row)
- for(int col=0;col<COLS;++col)
- DotProduct(row,col,final_matrix,initial_matrix);
- }
- int main(int argc, char* argv[])
- {
- int i;
- pthread_t thr[THREADS];
- //Barrier initialization
- if(pthread_barrierattr_init(&barr,NULL,THREADS))
- {
-
- printf("Could not create a barrier\n");
- return -1;
- }
- for(i=0;i<THREADS;++i)
- {
- if(pthread_create(&thr[i],NULL,&entry_point, (void*)i))
- {
-
- printf("Could not create thread %d\n", i);
- return -1;
- }
- }
- for(i=0;i<THREADS;++i)
- {
- if(pthread_join(thr[i],NULL))
- {
-
- printf("Could not join thread %d\n", i);
- return -1;
- }
- }
- double det = determinant(initial_matrix);
- printf("The determinant of M^4 = %f\n", det);
- return 0;
-
- }
-
復(fù)制代碼 這段程序產(chǎn)生出許多個(gè)線程,并且分配給每個(gè)線程計(jì)算矩陣乘法的一部分,然后每個(gè)線程使用這次計(jì)算的結(jié)果,繼續(xù)進(jìn)行下一步的計(jì)算:另一個(gè)矩陣的乘法
幾點(diǎn)關(guān)于API的說明:
barrier 變量必須在最開始聲名為全局變量
barrier 變量的初始化必須在main函數(shù)里進(jìn)行初始化
在點(diǎn)上每一個(gè)線程都會(huì)等待它的對(duì)端完成工作
注意
在程序頂部的宏定義 _XOPEN_SOURCE 是非常重要的;如果沒有這個(gè)變量,那么barrier類型就會(huì)在pthread.h中被屏蔽掉,這個(gè)定義必須在所有的頭文件引用之前被定義出來 |
|