Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*All right reserved awinsyspro.com 2019*/
- /*Mutex application in thread Synchronization*/
- /*This example demonstrate printing odd and even number*/
- #include<Windows.h>
- #include<iostream>
- using namespace std;
- //Global Handle for Mutex
- HANDLE hMutex = NULL;
- //Global variable
- int gCount = 1;
- //STEP-3 Thread function for odd and even numbers
- DWORD WINAPI ThreadFunEven(LPVOID lpParam)
- {
- while (gCount<10)
- {
- //Mutex lock
- WaitForSingleObject(hMutex, INFINITE);
- //Critical Section Code
- if (gCount%2==0)
- {
- cout << "Even - " << gCount++ << endl;
- }
- //Mutex unlock
- ReleaseMutex(hMutex);
- }//while-loop
- return 0;
- }
- DWORD WINAPI ThreadFunOdd(LPVOID lpParam)
- {
- while (gCount<10)
- {
- //Mutex lock
- WaitForSingleObject(hMutex, INFINITE);
- //Critical Section Code
- if (gCount % 2 == 1)
- {
- cout << "odd - " << gCount++ << endl;
- }
- //Mutex unlock
- ReleaseMutex(hMutex);
- }//while-loop
- return 0;
- }
- int main()
- {
- //Local Variable
- HANDLE hThread1 = NULL;
- HANDLE hThread2 = NULL;
- //STEP-1 Create Mutex function
- hMutex = CreateMutex(
- NULL,//Mutex Security Attribute
- FALSE,//ownership
- NULL);//mutex name
- if (NULL == hMutex)
- {
- cout << "Mutex Creation Failed" << endl;
- cout << "Error No - " << GetLastError() << endl;
- }
- cout << "Mutex Creation Success" << endl;
- //STEP-2 Create two thread function for odd and even
- hThread1 = CreateThread(
- NULL, //Security Attribute
- 0, //Default Stack Size
- &ThreadFunEven,//ThreadStart Address
- NULL, //Parameter
- 0, //Flags
- 0); //ThreadID
- hThread2 = CreateThread(
- NULL, //Security Attribute
- 0, //Default Stack Size
- &ThreadFunOdd,//ThreadStart Address
- NULL, //Parameter
- 0, //Flags
- 0); //ThreadID
- //STEP-4 CloseHandle for thread1 & Thread2
- CloseHandle(hThread1);
- CloseHandle(hThread2);
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement