Created
April 2, 2020 15:53
-
-
Save lehaiquantb/e5378626533bcb1f1c8ef0eb99174e27 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <windows.h> | |
CRITICAL_SECTION cs; | |
using namespace std; | |
static long num_steps = 1000000; | |
double step, pi; | |
double sum = 0.0; | |
DWORD WINAPI calSum(LPVOID p) { | |
int *tmp = (int*)p; | |
EnterCriticalSection(&cs); | |
double x; | |
for (int i = *tmp; i < num_steps; i += 4) { | |
x = (i + 0.5) * step; | |
sum = sum + 4.0 / (1.0 + x * x); | |
} | |
LeaveCriticalSection(&cs); | |
return 0; | |
} | |
int main() | |
{ | |
int param[4]; | |
HANDLE hThreads[4]; | |
InitializeCriticalSection(&cs); | |
step = 1.0 / (double)num_steps; | |
for (int i = 0; i < 4; i++) | |
{ | |
param[i] = i; | |
hThreads[i] = CreateThread(0,0,calSum,¶m[i],0,0); | |
} | |
WaitForMultipleObjects(4,hThreads,TRUE,INFINITE); | |
DeleteCriticalSection(&cs); | |
pi = step * sum; | |
printf("Pi = % f\n", pi); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment