问一个多线程基础问题

APIandMFC APIandMFC 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
int index=0;
int tickets=100;
HANDLE hMutex;
DWORD WINAPI FunProc1(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
cout<<"Thread1 is telling ticket:"<<tickets--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI FunProc2(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
cout<<"Thread2 is telling ticket:"<<tickets--<<endl;
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
void main()
{
HANDLE hThread1,hThread2;
hThread1=CreateThread(NULL,0,FunProc1,NULL,0,NULL);
hThread2=CreateThread(NULL,0,FunProc2,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex=CreateMutex(NULL,FALSE,"tickets");
if(hMutex)
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only one instance can run!"<<endl;
return;
}
}
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(4000);
}


1 if(hMutex)这是在判断什么?

2if(ERROR_ALREADY_EXISTS==GetLastError())这是在判断什么?

3CloseHandle(hThread1);表示什么?

4WaitForSingleObject(hMutex,INFINITE) 主线程为什么还有写这个?

5两次"ReleaseMutex(hMutex);"分别释放的什么?
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
APIandMFC
进程/线程/DLL 15,465 成员 49,169 内容