Advertisement
Guest User

Untitled

a guest
Nov 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <windows.h>
  2. #include <iostream>
  3. #define NumThread 9
  4. #define dokladnosc 9999999999
  5. using namespace std;
  6.  
  7.  
  8. HANDLE mutex;
  9. struct Dane
  10. {
  11.     double pi;
  12.     int i;
  13.     int arg;
  14. };
  15.  
  16. double pi(int n) {
  17.     double sum = 0.0;
  18.     int sign = 1;
  19.     for (int i = 0; i < n; ++i) {
  20.         sum += sign / (2.0*i + 1.0);
  21.         sign *= -1;
  22.     }
  23.     return 4.0*sum;
  24. }
  25. DWORD WINAPI watek(LPVOID LpParam) {
  26.     Dane* dane = (Dane*)LpParam;
  27.  
  28.     WaitForSingleObject(mutex, INFINITE);
  29.     while(dane->i < dokladnosc)
  30.     {
  31.         dane->pi += dane->arg / (2.0*dane->i +1);
  32.         dane->arg *= -1;
  33.         dane->i++;
  34.     }
  35.     ReleaseMutex(mutex);
  36.     cout << "exit" << endl;
  37.  
  38.     return 0;
  39. }
  40.  
  41. int main()
  42. {
  43.     DWORD id;
  44.     Dane* dane = new Dane(); HANDLE w[NumThread];
  45.    
  46.     dane->arg = 1;
  47.     dane->pi = 0;
  48.     dane->i = 0;
  49.     mutex = CreateMutex(NULL, false, NULL);
  50.  
  51.     cout << pi(dokladnosc)<<endl;
  52.  
  53.     for (int i = 0; i < NumThread; ++i)
  54.     {
  55.         w[i] = CreateThread(NULL, 0, watek, dane, 0, &id);
  56.     }
  57.  
  58.     WaitForMultipleObjects(NumThread, w, true, 10000);
  59.     cout << dane->pi*4 << endl;
  60.  
  61.     for (int i = 0; i < NumThread; ++i)
  62.     {
  63.         CloseHandle(w[i]);
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement