资源简介

并行计算三种方式计算π:概率法,积分法,级数法,代码中包括计算量和线程个数设置。
使用时进行编译后输入相应提示的数值即可,例如N=100000 t=8

资源截图

代码片段和文件信息

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  

double pi = 0.0;
long long m = 0;
long long N; //投的点的个数
int t; //线程数量
pthread_mutex_t lock;

void *thread(void *ID){
long id = (long) ID;
long long i;
long long length = N/t;
long long mi = 0;
for(i = 0;i < length;i++){
float x = rand()/(RAND_MAX + 1.0);
float y = rand()/(RAND_MAX + 1.0);
if ((x*x + y*y) <= 1.0)
mi++;
}

pthread_mutex_lock(&lock);
m += mi;
  pthread_mutex_unlock(&lock);
}


int main(){
int i; //用于遍历
pthread_mutex_init(&lockNULL);
pthread_t *threads;
threads=(pthread_t *)malloc(sizeof(pthread_t)*t);

//获取输入
printf(“Please enter the number of N: “);
scanf(“%ld“&N);
printf(“Please enter the number of threads (t): “);
scanf(“%d“&t);
printf(“\n“);


for(i=0;i pthread_create(&threads[i]NULLthread(void*)i); // 创建t个线程,并将线程标记为i
   }


for(i=0;i  {
         pthread_join(threads[i]NULL);
   }


pi = 4.0 * m/N;
printf(pi);

pthread_mutex_destroy(&lock);
return 0;
}


 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----
     文件        1090  2020-03-22 22:20  积分法.c
     文件        1348  2020-03-22 22:18  级数法.c
     文件        1250  2020-03-22 22:18  概率法.c

评论

共有 条评论