Created
April 1, 2020 15:07
-
-
Save SangSama/dc7d008b5953e86e62abf68aba12d595 to your computer and use it in GitHub Desktop.
This file contains hidden or 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> | |
#include <list> | |
#include <iterator> | |
using namespace std; | |
CRITICAL_SECTION cs; | |
static long num_steps = 100000; | |
double step, pi; | |
double sum = 0.0; | |
DWORD WINAPI CaculaSum(LPVOID p) { | |
// em Chưa convert được LPVOID thành list | |
list<int> arrs = (list<int>) p; | |
double x; | |
EnterCriticalSection(&cs); // đầu vào đợi | |
for (list <int> ::iterator it = g.begin(); it != g.end(); ++it) { | |
x = (*it + 0.5) * step; | |
sum = sum + 4.0 / (1.0 + x * x); | |
} | |
LeaveCriticalSection(&cs);// Xong thì ra | |
return 0; | |
} | |
int main() | |
{ | |
list<int> params1; | |
list<int> params2; | |
list<int> params3; | |
list<int> params4; | |
HANDLE hThreads[4]; | |
InitializeCriticalSection(&cs); | |
step = 1.0 / (double)num_steps; | |
for (int i = 0; i < num_steps; i++) { | |
if (i % 4 == 0) { | |
params1.push_back(i); | |
} | |
if (i % 4 == 1) { | |
params2.push_back(i); | |
} | |
if (i % 4 == 2) { | |
params3.push_back(i); | |
} | |
if (i % 4 == 3) { | |
params4.push_back(i); | |
} | |
} | |
hThreads[0] = CreateThread(0, 0, CaculaSum, ¶ms1, 0, 0); | |
hThreads[1] = CreateThread(0, 0, CaculaSum, ¶ms2, 0, 0); | |
hThreads[2] = CreateThread(0, 0, CaculaSum, ¶ms3, 0, 0); | |
hThreads[3] = CreateThread(0, 0, CaculaSum, ¶ms4, 0, 0); | |
WaitForMultipleObjects(4, hThreads, TRUE, INFINITE); // đa luồng | |
pi = step * sum; | |
std::cout<< pi; | |
DeleteCriticalSection(&cs); // xóa luồng | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment