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

#include
#include
#include
#include
#include
#include
#include
#include
#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:"<

你可能感兴趣的:(一些代码)