蒙特卡洛法多线程求圆周率

#include<iostream>
#include<string>
#include<pthread.h>
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<cstdio>
#include<sys/time.h>
#define MAX 100000000
using namespace std;
double result = 0;
int thread_num;
int Every_P;
pthread_mutex_t mut;
void *t_hread(void *arg){
    int m = *(int*)arg;
    if(m != thread_num - 1){
        for(int i = m * Every_P;i < (m + 1) * Every_P;i++){
	    	double x = sqrt(MAX) * sqrt(MAX - ((i + 0.5)/MAX)*(i + 0.5));
	    	int xx = x;
	    	double count;
	    	if((x - xx) > 0.5){
				count = xx + 1; 		
	    	}
	    	else{
				count = xx;
	    	}
	    	pthread_mutex_lock(&mut);
	    	result = result + (double)count/MAX;
	    	pthread_mutex_unlock(&mut);							
		}	
    }
    if(m == thread_num - 1){
		for(int i = m * Every_P;i < MAX;i++){
	   		double x = sqrt(MAX) * sqrt(MAX - ((i + 0.5)/MAX)*(i + 0.5));
	    	int xx = x;
	    	double count;
	    	if((x - xx) > 0.5){
				count = xx + 1; 		
	    	}
	    	else{
				count = xx;
	    	}
	    	pthread_mutex_lock(&mut);
	    	result = result + (double)count/MAX;
	    	pthread_mutex_unlock(&mut);			
		}
    }  
}
int main(int argc,char *argv[]){
    thread_num = atoi(argv[1]);
    pthread_t thread[thread_num];
    Every_P = MAX/thread_num;
    pthread_mutex_init(&mut,NULL);
    int id[thread_num];
    struct timeval begin,end;
    gettimeofday(&begin,NULL);
    for(int i = 0;i < thread_num;i++){
		id[i] = i;
        int err = pthread_create(&thread[i],NULL,t_hread,(void*)&id[i]);
    }
    for(int i = 0;i < thread_num;i++){
		pthread_join(thread[i],NULL);
    }
    gettimeofday(&end,NULL);
    double pi = result/MAX * 4;
    cout<<"pi is:"<<fixed<<setprecision(15)<<pi<<endl;
    int time = (end.tv_sec - begin.tv_sec) * 1000000 + (end.tv_usec - begin.tv_usec);
    printf("time: %d us\n", time);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yy64578537/article/details/51543193