⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pi.c

📁 用PTHREAD编写的并行计算pi值的并行程序!
💻 C
字号:
#include <stdio.h>
#include <pthread.h>
#include<time.h>

int  no_threads;
long int N;
long int global_index=0;
double pi=0.0;
pthread_mutex_t mutex1;

void *slave(void *ignored)
{
long int local_index;
double  partial_pi=0.0;
double  p,q,m;

do{
        pthread_mutex_lock(&mutex1);
        local_index=global_index;
        global_index++;
        pthread_mutex_unlock(&mutex1);

        if(local_index<N){
 p=(local_index+0.5)/N;
 q=p*p+1;
 m=4/(q*N);
 partial_pi+=m;
/*printf("\n%f",partial_pi);*/
}
}while (local_index<N);

pthread_mutex_lock(&mutex1);
pi+=partial_pi;
pthread_mutex_unlock(&mutex1);
return;
}

main()
{
int i;
time_t begin_time,end_time;
printf("\nplease input the no_threads:");
scanf("%d",&no_threads);
pthread_t thread[no_threads];

pthread_mutex_init(&mutex1,NULL);
printf("Please input the N:");
scanf("%d",&N);

begin_time=time((time_t*)0);
for(i=0;i<no_threads;i++)
        if(pthread_create(&thread[i],NULL,slave,NULL)!=0)
                perror("Pthread_create fails");
for(i=0;i<no_threads;i++)
        if(pthread_join(thread[i],NULL)!=0)
                perror("Pthread_join fails");
end_time=time((time_t*)0);
printf("The PI  is %lf\n",pi);
printf("Total time is %lf(s)\n",difftime(end_time,begin_time));
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -