// Parallel.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
static long num_steps = 100000;
const int numThreads = 4;
double step, pi;
CRITICAL_SECTION g_cs;
double sum = 0.0;
DWORD WINAPI countFunc(LPVOID pArg) {
double x;
int i;
int temp = *(int *)pArg;
int start = (temp*num_steps) / 4;
int end = start + num_steps / 4;
for (i = start; i < end; i++) {
EnterCriticalSection(&g_cs);
x = (i + 0.5)*step;
sum = sum + 4.0 / (1.0 + x*x);
LeaveCriticalSection(&g_cs);
}
return 0;
}
void main()
{
int i;
HANDLE hThread[numThreads];
step = 1.0 / (double)num_steps;
int tNum[numThreads];
InitializeCriticalSection(&g_cs);
for (int i = 0; i < numThreads; i++) {
tNum[i] = i;
hThread[i] = CreateThread(NULL, 0, countFunc, (LPVOID)&tNum[i], 0, NULL);
}
WaitForMultipleObjects(numThreads, hThread, TRUE, INFINITE);
DeleteCriticalSection(&g_cs);
pi = step * sum;
printf("PI = %12.9f\n", pi);
system("pause");
}
中值積分定理計算PI值的多線程實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.