Skip to content

Instantly share code, notes, and snippets.

@lehaiquantb
Created April 2, 2020 15:53
Show Gist options
  • Save lehaiquantb/e5378626533bcb1f1c8ef0eb99174e27 to your computer and use it in GitHub Desktop.
Save lehaiquantb/e5378626533bcb1f1c8ef0eb99174e27 to your computer and use it in GitHub Desktop.
#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,&param[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