线程同步之生产者与消费者问题

转载自:http://blog.csdn.net/morewindows/article/details/7577591

代码:

#include <process.h>
#include <Windows.h>
#include <iostream>
using namespace std;

CRITICAL_SECTION g_cs;

HANDLE g_hPoolEmpty, g_hPoolFull;
int g_nNumProduct;//表示缓存区的产品数量

UINT WINAPI Product(PVOID pNum)
{
	WaitForSingleObject(g_hPoolEmpty, INFINITE); //当获得信号量时,信号量的计数减1,表示有一个线程使用信号量。当有空的时间,就可以生产了
	ReleaseSemaphore(g_hPoolFull, 1, NULL);      //信号量的计数加1,此时释放是为了让其它线程可以运行

	EnterCriticalSection(&g_cs);
	g_nNumProduct++;
	cout << "产生1个后的数量为 :" << g_nNumProduct << endl;
	LeaveCriticalSection(&g_cs);

	return 0;
}

UINT WINAPI Customer(PVOID pNum)
{
	WaitForSingleObject(g_hPoolFull, INFINITE);//当有东西的时候,才可以消费,记住当g_hPoolFull为0时,就为不触发状态,就不能获得信号
	ReleaseSemaphore(g_hPoolEmpty, 1, NULL);

	EnterCriticalSection(&g_cs);
	g_nNumProduct--;
	cout << "消费1个后的数量为 :" << g_nNumProduct << endl;
	LeaveCriticalSection(&g_cs);
	return 0;
}

void main()
{
	g_hPoolEmpty = CreateSemaphore(NULL, 10, 10, NULL);//表示有10个空的资源等着被使用,触发状态
	g_hPoolFull  = CreateSemaphore(NULL, 0, 10, NULL);//表示当前有0个资源等着被使用,示触发状态
	InitializeCriticalSection(&g_cs);
	g_nNumProduct = 0;

	HANDLE hThread[8];

	int i;
	for (i = 0; i < 5; i++)
	{
		hThread[i] = (HANDLE)_beginthreadex(NULL, 0, Product, NULL, 0, NULL);
	}

	for (i = 5; i < 8; i++)
	{
		hThread[i] = (HWND)_beginthreadex(NULL, 0, Customer, NULL, 0, NULL);
	}

	WaitForMultipleObjects(8, hThread, TRUE, INFINITE);

	CloseHandle(g_hPoolEmpty);
	CloseHandle(g_hPoolFull);
	DeleteCriticalSection(&g_cs);
}

 

posted @ 2013-09-23 20:04  Fly Hawk  阅读(219)  评论(0编辑  收藏  举报