#include #include using namespace std; int a[10] = {-2,8,7,0,4,6,18,20,-8,5}; int A; HANDLE hSemaphore; CRITICAL_SECTION cs; DWORD WINAPI work(LPVOID) { printf("input sleep:"); int t; scanf_s("%d", &t); int i, k = 0; for (i = 0; i < 10; i++) { if (a[i] > A) { a[k] = a[i]; k++; ReleaseSemaphore(hSemaphore, 1, NULL); Sleep(t); } } for (i = k; k < 10; k++) { a[k] = 0; ReleaseSemaphore(hSemaphore, 1, NULL); Sleep(t); } return 0; } DWORD WINAPI SumElement(LPVOID) { int sum_elem = 0; EnterCriticalSection(&cs); for (int i = 0; i < 10; i++) { sum_elem += a[i]; } LeaveCriticalSection(&cs); printf("Sum = "); printf("%d\n", sum_elem); return 0; } int main() { int i; HANDLE hWork, hSum; DWORD IDThread; printf("An initial state of the array: "); for (i = 0; i < 10; i++) printf("%d ", a[i]); printf("\n"); printf("Input A: "); scanf_s("%d", &A); hSemaphore=CreateSemaphore(NULL, 0, 10, NULL); if (hSemaphore == NULL) return GetLastError(); hWork = CreateThread(NULL, 0, work, NULL, 0, &IDThread); hSum = CreateThread(NULL, 0, SumElement, NULL, 0, &IDThread); if (hWork == NULL) return GetLastError(); if (hSum == NULL) return GetLastError(); InitializeCriticalSection(&cs); for (i = 0; i < 10; i++) { EnterCriticalSection(&cs); WaitForSingleObject(hSemaphore, INFINITE); printf("%d ", a[i]); cout.flush(); LeaveCriticalSection(&cs); } printf("\n"); CloseHandle(hSemaphore); CloseHandle(hWork); CloseHandle(hSum); DeleteCriticalSection(&cs); //WaitForSingleObject(work, INFINITE); scanf_s("%d", 00); return 0; }