#include <stdio.h>
#include <windows.h>
#include<iostream>
#include <process.h>
#include <time.h>
using namespace std;
BOOL SetConsoleColor(WORD wAttributes)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole == INVALID_HANDLE_VALUE)
return FALSE;
return SetConsoleTextAttribute(hConsole, wAttributes);
}
HANDLE Signal_full;
HANDLE Signal_empty;
CRITICAL_SECTION g_cs;
const int products=15;
const int NUMBER = 10;
int cache[NUMBER];
int pro_i=0, con_j=0;
int cur_product = 1;
unsigned int __stdcall ProducerThreadFun(void* pM)
{
//int ID = *(int*)pM;
while (true)
{
WaitForSingleObject(Signal_empty, INFINITE);
//生产一个物品
EnterCriticalSection(&g_cs);
if (cur_product > products)
{
LeaveCriticalSection(&g_cs);
break;
}
cache[pro_i] = cur_product;
cout << "编号为 " << GetCurrentThreadId() << " 的生产者在 " << pro_i << " 生产了物品 " << cur_product << endl;
pro_i = (pro_i + 1) % NUMBER;
++cur_product;
LeaveCriticalSection(&g_cs);
ReleaseSemaphore(Signal_full, 1, NULL);
Sleep(rand() % 100 + 1);
}
cout << "编号为 " << GetCurrentThreadId() << " 的生产者结束线程\n";
return 0;
}
unsigned int __stdcall ConsumerThreadFun(void* pM)
{
while (true)
{
WaitForSingleObject(Signal_full, 3000);
//消费一个物品
EnterCriticalSection(&g_cs);
if (cur_product > products)
{
LeaveCriticalSection(&g_cs);
break;
}
cout << " 编号为 " << GetCurrentThreadId() << " 的消费者在 " << con_j << " 消费了物品 " << cache[con_j] << endl;
con_j = (con_j + 1) % NUMBER;
LeaveCriticalSection(&g_cs);
ReleaseSemaphore(Signal_empty, 1, NULL);
Sleep(rand() % 100 + 1);
}
cout << " 编号为 " << GetCurrentThreadId() << " 的消费者结束线程\n";
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(NULL));
//2个生产者、5个消费者、10个缓存、生存15个物品
HANDLE threads[7];
Signal_full = CreateSemaphore(NULL, 0, 10, NULL);
Signal_empty = CreateSemaphore(NULL,10, 10, NULL);
InitializeCriticalSection(&g_cs);
for (int i = 0; i < 2; ++i)
threads[i] = (HANDLE)_beginthreadex(NULL, 0, ProducerThreadFun, NULL, 0, NULL);
for (int i = 2; i < 7;++i)
threads[i] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
WaitForMultipleObjects(7, threads, TRUE, INFINITE);
//Sleep(5000);
for (int i = 0; i < 7; ++i)
CloseHandle(threads[i]);
CloseHandle(Signal_full);
CloseHandle(Signal_empty);
DeleteCriticalSection(&g_cs);
cout << endl;
system("pause");
return 0;
}