Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <iostream>
- using namespace std;
- int n = 0;
- int k = 0;
- int *a, *b, sum = 0;
- HANDLE hSemaphore1, hSemaphore2, hSemaphore3;
- DWORD WINAPI work(LPVOID){
- int time = 0;
- cout << "Enter time: ";
- cin >> time;
- b = new int[n];
- bool flag = false;
- int q = 0;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- if (i != j) {
- if (a[i] == a[j]) {
- flag = false;
- break;
- }
- else {
- flag = true;
- }
- }
- }
- if (flag) {
- b[q] = a[i];
- q++;
- ReleaseSemaphore(hSemaphore1, 1, NULL);
- Sleep(time);
- }
- }
- int qq = q;
- flag = true;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < q; j++) {
- if (a[i] != b[j]) {
- flag = true;
- }
- else {
- flag = false;
- break;
- }
- }
- if (flag) {
- b[qq] = a[i];
- qq++;
- ReleaseSemaphore(hSemaphore1, 1, NULL);
- Sleep(time);
- }
- }
- a = b;
- return 0;
- }
- DWORD WINAPI SumElement(LPVOID) {
- WaitForSingleObject(hSemaphore2, INFINITE);
- for (int i = 0; i < k; i++) {
- sum += b[i];
- }
- WaitForSingleObject(hSemaphore3, INFINITE);
- cout << endl << sum << endl;
- return 0;
- }
- int main()
- {
- HANDLE hThread1, hThread2;
- DWORD IDThread1, IDThread2;
- cout << "\n\tEnter size array: ";
- cin >> n;
- a = new int[n];
- cout << "\n\tSize: " << n << "\n";
- for (int i = 0; i < n; i++) {
- cout << "Enter " << i << " element :";
- cin >> a[i];
- }
- for (int i = 0; i < n; i++)
- cout << a[i] << ' ';
- cout << endl;
- cout << "\n\tEnter k: ";
- cin >> k;
- hSemaphore1 = CreateSemaphore(NULL, 0, n, NULL);
- hSemaphore2 = CreateSemaphore(NULL, 0, 1, NULL);
- hSemaphore3 = CreateSemaphore(NULL, 0, 1, NULL);
- if (hSemaphore1 == NULL)
- return GetLastError();
- if (hSemaphore2 == NULL)
- return GetLastError();
- hThread1 = CreateThread(NULL, 0, work, NULL, 0, &IDThread1);
- hThread2 = CreateThread(NULL, 0, SumElement, NULL, 0, &IDThread2);
- for (int i = 0; i < n; i++) {
- WaitForSingleObject(hSemaphore1, INFINITE);
- cout << b[i] << ' ';
- cout.flush();
- if (i == k) {
- ReleaseSemaphore(hSemaphore2, 1, NULL);
- }
- }
- ReleaseSemaphore(hSemaphore3, 1, NULL);
- CloseHandle(hSemaphore1);
- CloseHandle(hSemaphore2);
- CloseHandle(hThread1);
- CloseHandle(hThread2);
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement