1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
   | #include<Windows.h> #include<iostream> #include<string> using namespace std; long long sum = 0; int maxn = 100000; CRITICAL_SECTION cs; DWORD WINAPI thread1(PVOID pvParam) {      	EnterCriticalSection(&cs); 	cout << "Threat1 is running!" << endl; 	LeaveCriticalSection(&cs); 	 	HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, TRUE, TEXT("event1")); 	for (int i = 0; i <= maxn; i += 2) { 		 		WaitForSingleObject(hEvent, INFINITE); 		 		 		 		sum += i; 		 		SetEvent(hEvent); 	} 	return 0; } DWORD WINAPI thread2(PVOID pvParam) { 	EnterCriticalSection(&cs); 	cout << "Threat2 is running!" << endl; 	LeaveCriticalSection(&cs); 	HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, TRUE, TEXT("event1")); 	for (int i = 1; i <= maxn; i += 2) { 		WaitForSingleObject(hEvent, INFINITE); 		 		sum += i; 		SetEvent(hEvent); 	} 	return 0; } long long res() { 	long long s = 0; 	for (int i = 1; i <= maxn; i++) { 		s += i; 	} 	return s; } int main() { 	InitializeCriticalSection(&cs); 	 	HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("event1")); 	 	 	 	cout << "event1 was created and fIinitialState is False \n"; 	 	SetEvent(hEvent); 	 	HANDLE hThreat1 = CreateThread(NULL, 0, thread1, NULL, 0, NULL); 	HANDLE hThreat2 = CreateThread(NULL, 0, thread2, NULL, 0, NULL); 	EnterCriticalSection(&cs); 	cout << "threat1 and threat2 were created!\n"; 	LeaveCriticalSection(&cs);
  	 	 	HANDLE hThreats[2] = { hThreat1,hThreat2 }; 	WaitForMultipleObjects(2, hThreats, TRUE, INFINITE); 	cout << "Mutil threats result of the sum from 1 to "<<maxn<<" is " << sum << endl; 	cout << "Right result of the sum from 1 to " << maxn << " is " << res() << endl; 	return 0; }
   |