Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. /*All right reserved awinsyspro.com 2019*/
  2. /*Mutex application in thread Synchronization*/
  3. /*This example demonstrate printing odd and even number*/
  4. #include<Windows.h>
  5. #include<iostream>
  6. using namespace std;
  7. //Global Handle for Mutex
  8. HANDLE hMutex = NULL;
  9. //Global variable
  10. int gCount = 1;
  11. //STEP-3 Thread function for odd and even numbers
  12. DWORD WINAPI ThreadFunEven(LPVOID lpParam)
  13. {
  14. while (gCount<10)
  15. {
  16. //Mutex lock
  17. WaitForSingleObject(hMutex, INFINITE);
  18. //Critical Section Code
  19. if (gCount%2==0)
  20. {
  21. cout << "Even - " << gCount++ << endl;
  22. }
  23. //Mutex unlock
  24. ReleaseMutex(hMutex);
  25. }//while-loop
  26. return 0;
  27. }
  28. DWORD WINAPI ThreadFunOdd(LPVOID lpParam)
  29. {
  30. while (gCount<10)
  31. {
  32. //Mutex lock
  33. WaitForSingleObject(hMutex, INFINITE);
  34. //Critical Section Code
  35. if (gCount % 2 == 1)
  36. {
  37. cout << "odd - " << gCount++ << endl;
  38. }
  39. //Mutex unlock
  40. ReleaseMutex(hMutex);
  41. }//while-loop
  42. return 0;
  43. }
  44. int main()
  45. {
  46. //Local Variable
  47. HANDLE hThread1 = NULL;
  48. HANDLE hThread2 = NULL;
  49. //STEP-1 Create Mutex function
  50. hMutex = CreateMutex(
  51. NULL,//Mutex Security Attribute
  52. FALSE,//ownership
  53. NULL);//mutex name
  54. if (NULL == hMutex)
  55. {
  56. cout << "Mutex Creation Failed" << endl;
  57. cout << "Error No - " << GetLastError() << endl;
  58. }
  59. cout << "Mutex Creation Success" << endl;
  60. //STEP-2 Create two thread function for odd and even
  61. hThread1 = CreateThread(
  62. NULL, //Security Attribute
  63. 0, //Default Stack Size
  64. &ThreadFunEven,//ThreadStart Address
  65. NULL, //Parameter
  66. 0, //Flags
  67. 0); //ThreadID
  68.  
  69. hThread2 = CreateThread(
  70. NULL, //Security Attribute
  71. 0, //Default Stack Size
  72. &ThreadFunOdd,//ThreadStart Address
  73. NULL, //Parameter
  74. 0, //Flags
  75. 0); //ThreadID
  76. //STEP-4 CloseHandle for thread1 & Thread2
  77. CloseHandle(hThread1);
  78. CloseHandle(hThread2);
  79. system("PAUSE");
  80. return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement