#include<windows.h>
#include<stdio.h>
#include<time.h>
#include<math.h>
#define POINT_NUM 10000000//点的数目,尽量不适用N、M这些会出现命名冲突
#define THREAD_NUM 10 //线程数
DWORD Thread(int *pData)
{
double x, y;
srand(time(NULL));
for(int i = 0; i < POINT_NUM / THREAD_NUM; i++)
{
x = (double)(1.0 * rand() / RAND_MAX);
y = (double)(1.0 * rand() / RAND_MAX);
if(pow(x, 2) + pow(y, 2) <= 1.0)
(*pData) += 1;
}
return 0;
}
int main()
{
double pi;
int count[THREAD_NUM];
int total=0;
HANDLE h[THREAD_NUM];
for(int i=0;i<THREAD_NUM;i++)
{
count[i]=0;
h[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Thread, &count[i], 0, NULL);
if(h[i] == NULL)
printf("CreateThread Thread%d Error!\n",i);
Sleep(1000);
}
WaitForMultipleObjects(THREAD_NUM,h,TRUE,INFINITE);
for(int i = 0; i < THREAD_NUM; i++)
{
total+=(count[i]);
}
pi = 4.0 * total / POINT_NUM;
printf("pi:%f\n",pi);
return 0;
}