生产者消费者问题



#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值