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

来源:互联网 发布:淘宝售假扣48分重开店 编辑:程序博客网 时间:2024/05/21 17:54
#include<iostream>#include<string>#include<pthread.h>#include<cmath>#include<cstdlib>#include<iomanip>#include<cstdio>#include<sys/time.h>#define MAX 100000000using 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;}

0 0