问题描述
- 孙鑫视频第15章,多线程的创建,用互斥机制模拟火车票售票,我的问题,望大神指点
-
问题:当我设的总票数超过298时(比如500,1000),我的票都是从第298张开始卖的,正常的应该是总票数是多少张,就是从多少张开始卖的吧,当总票数小于298时,就是正常卖票,下面是我的代码,和运行结果的图片(当票数为500时),我的编译环境是vs 2008请大神指点
#include
#include
using namespace std;
DWORD WINAPI ThreadFun1(
In LPVOID lpParameter
);
DWORD WINAPI ThreadFun2(
In LPVOID lpParameter
);
static UINT tickets=500;
HANDLE hMutex;void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,ThreadFun1,NULL, 0,NULL);
hThread2=CreateThread(NULL,0,ThreadFun2,NULL, 0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
/*while(index++<1000)
cout<<"Main Thread is runningn";*/
hMutex=CreateMutex(NULL,FALSE,NULL);
Sleep(4000);
//Sleep(10);
}
DWORD WINAPI ThreadFun1(
In LPVOID lpParameter
)
{
/*while(index++<1000)
cout<<"Thread1 is runningn";*/while(TRUE) { WaitForSingleObject(hMutex,INFINITE); if(tickets>0) { cout<<"Thread1:"<<tickets--<<'n'; /*puts("Thread1:"); printf("%d",tickets); tickets--;*/ } else break; ReleaseMutex(hMutex); } return 0;
}
DWORD WINAPI ThreadFun2(
In LPVOID lpParameter
)
{
/*while(index++<1000)
cout<<"Thread1 is runningn";*/while(TRUE) { WaitForSingleObject(hMutex,INFINITE); if(tickets>0) cout<<"Thread2:"<<tickets--<<'n'; /*{ puts("Thread2:"); printf("%d",tickets); tickets--; }*/ else break; ReleaseMutex(hMutex); } return 0;
时间: 2024-10-24 20:28:02