#include <windows.h>
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
const int nPool = 5;
const int nProducer = 3;
const int nConsumer = 2;
int nProductId = 0;
bool bRunning = true;
// 线程互斥
HANDLE hMutex;
HANDLE hFull;
HANDLE hEmpty;
vector<int> vec;
DWORD WINAPI Product(LPVOID);
DWORD WINAPI Consume(LPVOID);
int main()
{
hMutex = CreateMutex(NULL, FALSE,NULL);
hFull = CreateSemaphore(NULL, nPool, nPool, NULL);
hEmpty = CreateSemaphore(NULL, 0, nPool, NULL);
HANDLE hProducter[nProducer];
for (int i = 0; i < nProducer; ++i)
hProducter[i] = CreateThread(NULL, 0, Product, NULL, 0, NULL);
HANDLE hConsumer[nConsumer];
for (int i = 0; i < nConsumer; ++i)
hConsumer[i] = CreateThread(NULL, 0, Consume, NULL, 0, NULL);
while (bRunning)
{
if (getchar())
bRunning = false;
}
vec.clear();
for (int i = 0; i < nProducer; ++i)
{
if (NULL != hProducter[i])
{
CloseHandle(hProducter[i]);
hProducter[i] = NULL;
}
}
for (int i = 0; i < nConsumer; ++i)
{
if (NULL != hConsumer[i])
{
CloseHandle(hConsumer[i]);
hConsumer[i] = NULL;
}
}
if (NULL != hMutex)
{
CloseHandle(hMutex);
hMutex = NULL;
}
if (NULL != hFull)
{
CloseHandle(hFull);
hFull = NULL;
}
if (NULL != hEmpty)
{
CloseHandle(hEmpty);
hEmpty = NULL;
}
return 0;
}
DWORD WINAPI Product(LPVOID para)
{
while (bRunning)
{
WaitForSingleObject(hFull, INFINITE);
WaitForSingleObject(hMutex, INFINITE);
++nProductId;
nProductId %= nPool;
vec.push_back(nProductId);
cout << "Product " << nProductId << " , the Product Number in Pool is " << vec.size() << endl;
Sleep(2000);
ReleaseMutex(hMutex);
ReleaseSemaphore(hEmpty, 1, NULL);
}
return 0;
}
DWORD WINAPI Consume(LPVOID para)
{
while (bRunning)
{
WaitForSingleObject(hEmpty, INFINITE);
WaitForSingleObject(hMutex, INFINITE);
vec.pop_back();
cout << "Consuem a product, and the Product Number in Pool is " << vec.size() << endl;
Sleep(1000);
ReleaseMutex(hMutex);
ReleaseSemaphore(hFull, 1, NULL);
}
return 0;
}