資源簡介
讀入第一個參數(shù)為線程數(shù),第二個參數(shù)為N,積分法計算pi,C+pthread實現(xiàn),附結果比較表

代碼片段和文件信息
#include?
#include?
#include?
#include?
#include?
#define?max_threads?512
double?local_res[max_threads];
int?num_threads?num_per_thread?N;
void?*compute_pi(void?*id)?{
int?index?=?*((int?*)id);
int?begin?=?index?*?num_per_thread;
int?end;
if(index?==?num_threads?-?1)
end?=?N;
else
end?=?begin?+?num_per_thread?-?1;
int?i;
double?lc?=?0.0;
for(i?=?begin;i?<=?end;i++){
double?tmp?=?(i?+?0.5)?/?N;
tmp?=?tmp?*?tmp?+?1;
tmp?=?4?/?(N?*?tmp);
lc?+=?tmp;
}
local_res[index]?=?lc;
}
int?main(int?argcchar?*argv[])?{
pthread_t?p_threads[max_threads];
double?result?=?0.0;
int?i;
int?*tmp;
struct?timeval?tv;
double?time_start?time_end;
num_threads?=?atoi(argv[1]);
N?=?atoi(argv[2]);
num_per_thread?=?N?/?num_threads;?
gettimeofday(&tv?NULL);
time_start?=?(double)tv.tv_sec?+?(double)tv.tv_usec?/?1000000.0;
for(i?=?0;i? tmp?=?(int?*)malloc(sizeof(int));
*tmp?=?i;
pthread_create(&p_threads[i]?NULL?compute_pi?(void?*)tmp);
}
for(i=?0;i? pthread_join(p_threads[i]?NULL);
result?+=?local_res[i];
}
gettimeofday(&tv?NULL);
time_end?=?(double)tv.tv_sec?+?(double)tv.tv_usec?/?1000000.0;
printf(“Computed?PI?=?%lf\n“?result);
printf(“Time?Consuming:?%lf\n“?time_end?-?time_start);
return?0;
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件???????1389??2009-12-12?23:10??線程ipc\pi.c
?????文件??????22528??2009-12-12?22:59??線程ipc\res.xls
?????目錄??????????0??2009-12-12?21:00??線程ipc
-----------?---------??----------?-----??----
????????????????23917????????????????????3
- 上一篇:樹莓派串口通信
- 下一篇:以太網(wǎng)ENC28J60 tcp udp
評論
共有 條評論