1. #include <windows.h>
  2. #include <iostream.h>
  3. DWORD WINAPI Fun1Proc(
  4. LPVOID lpParameter //thread data
  5. );
  6. DWORD WINAPI Fun2Proc(
  7. LPVOID lpParameter //thread data
  8. );
  9. int index = 0;
  10. int tickets = 100;
  11. HANDLE hMutex;
  12. void main()
  13. {
  14. HANDLE hThread1;
  15. HANDLE hThread2;
  16. // 仅允许有一个实列运行
  17. hMutex = CreateMutex(NULL, FALSE, "tickets");
  18. if (hMutex){
  19. DWORD dw = GetLastError();
  20. if (ERROR_ALREADY_EXISTS == dw){
  21. cout<<"only one instance can run!!"<<endl;
  22. return;
  23. }
  24. }
  25. // 创建线程
  26. hThread1 = CreateThread(NULL,0,Fun1Proc, NULL, 0, NULL);
  27. hThread2 = CreateThread(NULL,0,Fun2Proc, NULL, 0, NULL);
  28. CloseHandle(hThread1);
  29. CloseHandle(hThread2);
  30. // 创建互斥对像
  31. //hMutex = CreateMutex(NULL,TRUE,NULL);
  32. //WaitForSingleObject(hMutex,INFINITE);
  33. //ReleaseMutex(hMutex);
  34. //ReleaseMutex(hMutex);
  35. Sleep(4000);
  36. }
  37. //线程1入口
  38. DWORD WINAPI Fun1Proc(LPVOID lpParameter ){
  39. // WaitForSingleObject(hMutex,INFINITE);
  40. // cout<<"thread 1 run"<<endl;
  41. // return 0;
  42. //WaitForSingleObject(hMutex, INFINITE);
  43. while(TRUE){
  44. // 无限等待
  45. WaitForSingleObject(hMutex, INFINITE);
  46. if (tickets > 0){
  47. //Sleep(20);
  48. cout<<"thread1 sell ticket:"<<tickets--<<endl;
  49. }else{
  50. break;
  51. }
  52. // 释放对像
  53. ReleaseMutex(hMutex);
  54. }
  55. //ReleaseMutex(hMutex);
  56. return 0;
  57. }
  58. //线程2入口
  59. DWORD WINAPI Fun2Proc(LPVOID lpParameter ){
  60. // WaitForSingleObject(hMutex,INFINITE);
  61. // cout<<"thread 2 run"<<endl;
  62. // return 0;
  63. while(TRUE){
  64. WaitForSingleObject(hMutex, INFINITE);
  65. if (tickets > 0){
  66. //Sleep(40);
  67. cout<<"thread2 sell ticket:"<<tickets--<<endl;
  68. }else{
  69. break;
  70. }
  71. ReleaseMutex(hMutex);
  72. }
  73. return 0;
  74. }

这里写图片描述

版权声明:本文为laohaozi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/laohaozi/p/8266525.html