先贴代码
#include <Windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);
int index=0;
int tickets=100;
HANDLE hMutex;
int main(){
HANDLE hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
HANDLE hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL); //it does not close the thread
CloseHandle(hThread1);
CloseHandle(hThread2);
/*
while (index++<1000)
{
cout<<"main thread is running.index="<<index<<endl;
}*/
hMutex=CreateMutex(NULL,FALSE,NULL);
Sleep(4000);
return 0;
}DWORD WINAPI Fun1Proc(LPVOID lpParameter){
/*
while (index++<1000)
{
cout<<"thread1 is running.index="<<index<<endl;
}*/ WaitForSingleObject(hMutex,INFINITE);
while(TRUE){
if (tickets>0)
{
cout<<"thread1 sells ticket:"<<tickets--<<endl;
}
else{
break;
}
}
ReleaseMutex(hMutex);
return 0;
}DWORD WINAPI Fun2Proc(LPVOID lpParameter){ WaitForSingleObject(hMutex,INFINITE);
while(TRUE){
if (tickets>0)
{
cout<<"thread2 sells ticket:"<<tickets--<<endl;
}
else{
break;
}
}
ReleaseMutex(hMutex);
return 0;
}
照书上来说运行结果应该是完全由一个线程来执行完整个循环,
可为什么我运行的时候会出现交替的情况?
请各位大牛帮忙运行下看看,谢谢.