Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <windows.h>
  4. #include <cstdlib>
  5. #include <ctime>
  6. #include <thread>
  7. #include <mutex>
  8.  
  9. using namespace std;
  10.  
  11. int maximum=0;
  12.  
  13. void max1(int *mas, int n, mutex& mtx)
  14. {
  15.  
  16. for (int i = 0; i < n / 2; i++)
  17. {
  18. mtx.lock();
  19. if (mas[i] > maximum)
  20. {
  21. maximum = mas[i];
  22. }
  23. cout << "Fun1: mas[" << i << "] = " << mas[i] << " maximum = " << maximum << endl;
  24. mtx.unlock();
  25. Sleep(1000);
  26. }
  27.  
  28. }
  29.  
  30. void max2(int *mas, int n,mutex& mtx)
  31. {
  32. for (int i = n / 2; i < n; i++)
  33. {
  34. mtx.lock();
  35. if (mas[i] > maximum)
  36. {
  37. maximum = mas[i];
  38. }
  39. cout << "Fun2: mas[" << i << "] = " << mas[i] << " maximum = " << maximum << endl;
  40. mtx.unlock();
  41. Sleep(1000);
  42. }
  43.  
  44. }
  45.  
  46. void main()
  47. {
  48. int n;
  49. cout << "Size: ";
  50. cin >> n;
  51. int *mas = new int[n];
  52.  
  53. srand(time(NULL));
  54. for (int i = 0; i < n; i++)
  55. {
  56. mas[i] = rand() % 100;
  57. }
  58.  
  59. for (int i = 0; i < n; i++)
  60. {
  61. cout << mas[i] << " ";
  62. }
  63. cout << endl;
  64.  
  65. mutex mtx;
  66.  
  67. thread t1(max1, mas, n,ref(mtx));
  68. thread t2(max2, mas, n, ref(mtx));
  69.  
  70. t1.join();
  71. t2.join();
  72.  
  73.  
  74.  
  75. cout << "Maximum = " << maximum << endl;
  76.  
  77. system("pause");
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement