课本上的蒙塔卡罗讲解为:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#define total 10000
#define p_num 10
int in = 0;
pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;
void* cast (void* args)
{
int i;
float x,y;
int temp_in=0;
for(i=0; i< (total/p_num); i++){
x= (float)(rand() % 1001) * 0.001f;
y= (float)(rand() % 1001) * 0.001f;
if(y<x*x) temp_in++;
}
pthread_mutex_lock(&m);
in += temp_in;
pthread_mutex_unlock(&m);
}
int main(int argc, char *argv[]){
pthread_t thread[p_num];
int i;
for (i=0;i<p_num;i++)
{
if(pthread_create(&thread[i], NULL, cast, NULL))
perror("Pthread Create Fails");
}
for (i=0;i<p_num;i++)
{
if(pthread_join(thread[i], NULL))
perror("Pthread Join Fails");
}
float shadow=(float) in/(float) total;
printf("in:%d\n",in);
printf("total:%d\n",total);
printf("the area of the shadow is:%f\n",shadow);
return 0;
}