最近在学操作系统,多线程的小例子。网上搜的。。比较基础,学一下。
#include <iostream>
#include <windows.h>
using namespace std;
HANDLE hMutex=NULL;
int num=100;
DWORD WINAPI Fun1(LPVOID lpParamter)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
if(num>0)
{
Sleep(20);
cout << "Thread 1 sell ticket : "<<num--<<endl;
}
else break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2(LPVOID lpParamter)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
if(num>0)
{
Sleep(80);
cout << "Thread 2 sell ticket : "<<num--<<endl;
}
else break;
ReleaseMutex(hMutex);
}
return 0;
}
int main()
{
HANDLE hThread_1 = CreateThread(NULL, 0, Fun1, NULL, 0, NULL);
HANDLE hThread_2 = CreateThread(NULL, 0, Fun2, NULL, 0, NULL);
CloseHandle(hThread_1);
CloseHandle(hThread_2);
hMutex=CreateMutex(NULL,FALSE,NULL);
if (hMutex)
{
if (ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only one instance can run!"<<endl;
return 0;
}
}
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);
Sleep(6000);//合理控制时间,否则票还没卖完,主进程就结束了。
return 0;
}