Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <windows.h>
  3. #include <iomanip>
  4.  
  5. using namespace std;
  6.  
  7. HANDLE* threads;
  8. HANDLE* events;
  9. const int N = 10000000;
  10. const int blockSize = 70000;
  11. const int maxBlocks = N / blockSize + 1;
  12. volatile double pi = 0;
  13. volatile long int blockNum;
  14.  
  15. DWORD WINAPI func(LPVOID lpParameter)
  16. {
  17. double _pi = 0;
  18. int num = (int)lpParameter;
  19. while (true)
  20. {
  21. int start = num * blockSize;
  22. int end = (num + 1)*blockSize;
  23. if (end > N)
  24. end = N;
  25. for (size_t i = start; i < end; i++)
  26. {
  27. _pi += 4 / (1 + pow((i + 0.5) / N, 2));
  28. }
  29. //cout << "thread finished countin (" << start << ": " << end << ") blocknum is " << blockNum << endl;
  30. SetEvent(events[(int)lpParameter]);
  31. num = InterlockedExchangeAdd(&blockNum, 1);
  32. if (blockNum > maxBlocks)
  33. break;
  34. SuspendThread(threads[(int)lpParameter]);
  35. }
  36. //cout << "finish" << endl;
  37. pi += _pi;
  38. return 0;
  39. }
  40.  
  41. int main()
  42. {
  43. int maxThreads;
  44. int freeThread = NULL;
  45.  
  46. cout << "Threads amount: ";
  47. cin >> maxThreads;
  48.  
  49. threads = new HANDLE[maxThreads];
  50. events = new HANDLE[maxThreads];
  51.  
  52. for (size_t i = 0; i < maxThreads; i++)
  53. {
  54. threads[i] = CreateThread(NULL, 0, func, (void*)i, CREATE_SUSPENDED, NULL);
  55. events[i] = CreateEventA(NULL, true, true, NULL);
  56. }
  57. blockNum = maxThreads;
  58.  
  59. double start = GetTickCount();
  60.  
  61. while (blockNum < maxBlocks)
  62. {
  63. freeThread = WaitForMultipleObjects(maxThreads, events, false, INFINITE) - WAIT_OBJECT_0;
  64. //cout << "free thread " << freeThread << "(blockNum is " << blockNum << ")" << endl;
  65. ResumeThread(threads[freeThread]);
  66. ResetEvent(events[freeThread]);
  67. }
  68. for (size_t i = 0; i < maxThreads; i++)
  69. {
  70. ResumeThread(threads[i]);
  71. }
  72. WaitForMultipleObjects(maxThreads, threads, true, INFINITE);
  73. pi = pi / N;
  74.  
  75. double end = GetTickCount();
  76.  
  77. cout << setprecision(75) << pi << endl;
  78. cout << "time: " << end - start << " ms" << endl;
  79.  
  80. /*for (size_t i = 0; i < maxThreads; i++)
  81. {
  82. CloseHandle(threads[i]);
  83. CloseHandle(events[i]);
  84. }*/
  85. system("pause");
  86. return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement