本人新手小白,在学习互斥对象这部分内容时编写的程序如下,为什么只有Thread1一直在执行而Thread2 没有呢?
#include "stdafx.h"
#include
#include
#include
using namespace std;
//using std::cout;
int tickets = 100;
HANDLE hMutex;
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
while (true)
{
WaitForSingleObject(hMutex,INFINITE);
if (tickets>0)
{
Sleep(1);
cout <<"Thread1 sell "<< tickets-- << endl;
}
ReleaseMutex(hMutex);
}
//cout << "Thread1 is running\n"<< endl;
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
)
{
while (true)
{
WaitForSingleObject(hMutex, INFINITE);
if (tickets>0)
{
Sleep(1);
cout <<"Thread2 sell "<< tickets-- << "\n" << endl;
}
ReleaseMutex(hMutex);
return 0;
}
}
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1 = CreateThread(
NULL, // SD
0, // initial stack size
Fun1Proc, // thread function
0, // thread argument
0, // creation option
NULL // thread identifier
);
CloseHandle(hThread1);
hThread2 = CreateThread(NULL,0,Fun2Proc,0,0,NULL);
CloseHandle(hThread1);
//char c[] = "tickets";
hMutex =CreateMutex(NULL,FALSE,"sasdasdfasdfa");
//WaitForSingleObject(hMutex, INFINITE);
//hMutex = CreateMutex(NULL, TRUE, "tickets");
//ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(4000);
system("pause");
}