Advertisement
Guest User

MUTEX

a guest
Jul 2nd, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <conio.h>
  3. #include <Windows.h>
  4. #include <fstream>
  5.  
  6. int mass[10];
  7. HANDLE hfirst, hsecond, hthird, hmutex;
  8. int i = 0;
  9. std::fstream file;
  10.  
  11. DWORD WINAPI ThirdThread(LPVOID param)
  12. {
  13.     if ((WaitForSingleObject(hfirst, INFINITE) == WAIT_OBJECT_0) && (WaitForSingleObject(hsecond, INFINITE) == WAIT_OBJECT_0)) {
  14.         file.close();
  15.         CloseHandle(hmutex);
  16.         std::cout << "\n\nYour massiv: ";
  17.         for (int j = 1; j <= i; ++j) {
  18.             std::cout << mass[j] << " ";
  19.         }
  20.     }
  21.     return 0;
  22. }
  23.  
  24. DWORD WINAPI SecondThread(LPVOID param)
  25. {
  26.     while (i < 10) {
  27.         if (OpenMutex(MUTEX_ALL_ACCESS, TRUE, L"ObjectMutex") != NULL) {
  28.             WaitForSingleObject(hmutex, INFINITE);
  29.             ++i;
  30.             mass[i] = mass[i - 1]  + i + i;
  31.             file << " " << mass[i] << " ";
  32.             std::cout << "Second thread works\n";
  33.             ReleaseMutex(hmutex);
  34.         }
  35.     }
  36.     return 0;
  37. }
  38.  
  39. DWORD WINAPI FirstThread(LPVOID param)
  40. {
  41.     while (i < 10) {
  42.         if (OpenMutex(MUTEX_ALL_ACCESS, TRUE, L"ObjectMutex") != NULL) {
  43.             WaitForSingleObject(hmutex, INFINITE);
  44.             ++i;
  45.             mass[0] = 0;
  46.             mass[i] = mass[i - 1] + i;
  47.             file  << mass[i];
  48.             std::cout << "First thread works\n";
  49.             ReleaseMutex(hmutex);
  50.         }
  51.     }
  52.     return 0;
  53. }
  54.  
  55. int main()
  56. {
  57.     DWORD first_param, id_first = 1, second_param, id_second = 1, third_param, id_third = 1;
  58.     file.open("text.txt", std::fstream::out);
  59.     std::cout << "Please, click any button to start \n";
  60.     getch();
  61.     hmutex = CreateMutex(NULL, FALSE, L"ObjectMutex");
  62.     hfirst = CreateThread(NULL, 0, FirstThread, &first_param, 0, NULL);
  63.     hsecond = CreateThread(NULL, 0, SecondThread, &second_param, 0, NULL);
  64.     hthird = CreateThread(NULL, 0, ThirdThread, &third_param, 0, NULL);
  65.     getch();
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement