Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include <iostream>
- #include <Windows.h>
- using std::cin;
- using std::cout;
- using std::endl;
- double result;
- __declspec(thread) double tempSum;
- const int N = 19000000;
- const int sizeOfBlock = 730519;
- double* results;
- struct Info
- {
- DWORD position;
- HANDLE event;
- bool calculationEnded;
- int numberOfThread;
- };
- DWORD WINAPI ThreadProc(LPVOID info)
- {
- tempSum = 0;
- while (!static_cast<Info*>(info)->calculationEnded)
- {
- const int posStartOfBlock = static_cast<Info*>(info)->position;
- for (int i = posStartOfBlock; i < posStartOfBlock + sizeOfBlock && i < N; ++i)
- {
- const double x = (i + 0.5) / N;
- tempSum += 4 / (1 + x * x);
- }
- SetEvent(static_cast<Info*>(info)->event);
- SuspendThread(GetCurrentThread());
- }
- results[static_cast<Info*>(info)->numberOfThread] = tempSum;
- return 0;
- }
- void winApiThreading(int numberOfThreads)
- {
- HANDLE* threads = new HANDLE[numberOfThreads];
- HANDLE* events = new HANDLE[numberOfThreads];
- results = new double[numberOfThreads];
- Info* infos = new Info[numberOfThreads];
- for (int i = 0; i < numberOfThreads; ++i)
- {
- infos[i].calculationEnded = false;
- infos[i].numberOfThread = i;
- infos[i].event = events[i] = CreateEvent(
- nullptr,
- FALSE,
- TRUE,
- nullptr);
- threads[i] = CreateThread(
- nullptr,
- 0,
- ThreadProc,
- &infos[i],
- CREATE_SUSPENDED,
- nullptr);
- }
- for (int i = 0; i < N; i += sizeOfBlock)
- {
- DWORD num = WaitForMultipleObjects(
- numberOfThreads, events,
- FALSE,
- INFINITE);
- infos[num].position = i;
- while (!ResumeThread(threads[num]));
- }
- WaitForMultipleObjects(numberOfThreads, events, TRUE, INFINITE);
- for (int i = 0; i < numberOfThreads; ++i)
- {
- infos[i].calculationEnded = true;
- ResumeThread(threads[i]);
- }
- WaitForMultipleObjects(numberOfThreads, threads, TRUE, INFINITE);
- for (int i = 0; i < numberOfThreads; ++i)
- result += results[i];
- result /= N;
- }
- void openMpThreading(int numberOfThreads)
- {
- #pragma omp parallel for schedule(dynamic, sizeOfBlock) num_threads(numberOfThreads) reduction(+:result)
- for (int i = 0; i < N; ++i)
- {
- const double x = (i + 0.5) / N;
- result += 4 / (1 + x * x);
- }
- result /= N;
- }
- int main()
- {
- int numberOfThreads;
- cout << "Number of threads\n> ";
- cin >> numberOfThreads;
- int typeOfThreading;
- cout << "\nSelect type of threading:\n1. WinAPI\n2. OpenMP\n> ";
- cin >> typeOfThreading;
- const DWORD startTime = GetTickCount();
- if (typeOfThreading == 1)
- winApiThreading(numberOfThreads);
- if (typeOfThreading == 2)
- openMpThreading(numberOfThreads);
- const DWORD executionTime = GetTickCount() - startTime;
- cout << "Result: " << result << endl;
- cout << "Time: " << executionTime << endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment