#include <iostream>
#include <windows.h>
using namespace std;
int index = 0,tickets = 100;
HANDLE mutex;
DWORD WINAPI func1(LPVOID lpParameter)
{
while (true)
{
WaitForSingleObject(mutex, INFINITE);
if (tickets > 0)
{
//Sleep(1);
cout << "卖票线程1:" << tickets-- << endl;
}
else
break;
ReleaseMutex(mutex);
}
return 0;
}
DWORD WINAPI func2(LPVOID lpParameter)
{
while (true)
{
WaitForSingleObject(mutex, INFINITE);
if (tickets > 0)
{
//Sleep(1);
cout << "卖票线程2:" << tickets-- << endl;
}
else
break;
ReleaseMutex(mutex);
}
return 0;
}
int main()
{
HANDLE hThread1,hThread2;
hThread1 = CreateThread(NULL, 0, func1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, func2, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
//while (index < 100)
//{
//cout << "主线程正在运行..." << endl;
// index++;
//}
mutex = CreateMutex(NULL,false,NULL);
Sleep(4000);
return 0;
}
C++多线程编程
最新推荐文章于 2023-07-19 00:34:37 发布