Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <iostream>
- #include <windows.h>
- #include <cstdlib>
- #include <ctime>
- #include <thread>
- #include <mutex>
- using namespace std;
- int maximum=0;
- void max1(int *mas, int n, mutex& mtx)
- {
- for (int i = 0; i < n / 2; i++)
- {
- mtx.lock();
- if (mas[i] > maximum)
- {
- maximum = mas[i];
- }
- cout << "Fun1: mas[" << i << "] = " << mas[i] << " maximum = " << maximum << endl;
- mtx.unlock();
- Sleep(1000);
- }
- }
- void max2(int *mas, int n,mutex& mtx)
- {
- for (int i = n / 2; i < n; i++)
- {
- mtx.lock();
- if (mas[i] > maximum)
- {
- maximum = mas[i];
- }
- cout << "Fun2: mas[" << i << "] = " << mas[i] << " maximum = " << maximum << endl;
- mtx.unlock();
- Sleep(1000);
- }
- }
- void main()
- {
- int n;
- cout << "Size: ";
- cin >> n;
- int *mas = new int[n];
- srand(time(NULL));
- for (int i = 0; i < n; i++)
- {
- mas[i] = rand() % 100;
- }
- for (int i = 0; i < n; i++)
- {
- cout << mas[i] << " ";
- }
- cout << endl;
- mutex mtx;
- thread t1(max1, mas, n,ref(mtx));
- thread t2(max2, mas, n, ref(mtx));
- t1.join();
- t2.join();
- cout << "Maximum = " << maximum << endl;
- system("pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement