我是靠谱客的博主 风趣悟空,这篇文章主要介绍多线程中互斥对象的使用示例,现在分享给大家,希望可以做个参考。

z摘自孙鑫书籍

#include <Windows.h>
#include <iostream>

DWORD WINAPI pThread(LPVOID lpParameter);//线程一
DWORD WINAPI sThread(LPVOID lpParameter);//线程二
using namespace std;
int tickets=100;
HANDLE hMutex;//互斥对象句柄
void main()
{
HANDLE hThread1;
HANDLE hThread2;

cout<<"start cell:"<<endl;
hThread1=CreateThread(NULL,0,pThread,NULL,0,NULL);
Sleep(10);
hThread2=CreateThread(NULL,0,sThread,NULL,0,NULL);


CloseHandle(hThread2);
CloseHandle(hThread1);

//创建互斥对象
hMutex=CreateMutex(NULL,false,NULL);

getchar();
//Sleep(5000);
}

//thread1
DWORD WINAPI pThread(LPVOID lpParameter)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if (tickets>0)
{
Sleep(1000);
cout<<"ppp cell ticket:"<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);

}
return 0;
}

//thread2
DWORD WINAPI sThread(LPVOID lpParameter)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if (tickets>0)
{
Sleep(1000);
cout<<"sss cell ticket:"<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);

}
return 0;
}


最后

以上就是风趣悟空最近收集整理的关于多线程中互斥对象的使用示例的全部内容,更多相关多线程中互斥对象内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(153)

评论列表共有 0 条评论

立即
投稿
返回
顶部