c++ 多线程
#include <windows.h> #include <iostream.h>
DWORD WINAPI Fun1Proc( LPVOID lpParameter );
DWORD WINAPI Fun2Proc( LPVOID lpParameter );
int index=0;
int tickets=100;
HANDLE hMutex;//互斥句柄
void main() {
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
hMutex=CreateMutex(NULL,FALSE,"MutexName");
//FALSE是创建的mutex不属于任何一个进程,每个mutex里有一个计数器,记录
//当前mutex所属的进程的调用次数
Sleep(4000); //主线程结束,其他的线程也要结束,故在此停留,把执行机会留给其他的子线程 }
DWORD WINAPI Fun1Proc( LPVOID lpParameter )
{ while(TRUE) {
WaitForSingleObject(hMutex,INFINITE);
//当计数器为0时,mutex的进程id标示为fun1进程,计数器为1
if(tickets>0) {
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else break;
ReleaseMutex(hMutex); //释放mutex,计数器值减1,此时为0
}
cout<<"thread1 is running"<<endl;
return 0;
}
DWORD WINAPI Fun2Proc( LPVOID lpParameter ) {
while(TRUE) {
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0) {
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
cout<<"thread2 is running"<<endl;
return 0;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。