利用生产者与消费者模型演示P,V操作
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
//producer and consumer
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
HANDLE hEvent1 = INVALID_HANDLE_VALUE;
HANDLE hEvent2 = INVALID_HANDLE_VALUE;
void __cdecl producerFun (void* param);
void __cdecl consumerFun (void* param);
queue
int ID = 1;
int storesize = 3;
int main()
{
hEvent1 = CreateEvent(NULL, TRUE, TRUE, L"producer");//producer event
hEvent2 = CreateEvent(NULL, TRUE, FALSE, L"consumer");//consumer event
uintptr_t hThread1 = _beginthread(producerFun, 0, NULL);
uintptr_t hThread2 = _beginthread(consumerFun, 0, NULL);
HANDLE hThread[] = { (HANDLE)hThread1 ,(HANDLE)hThread2 };
WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
CloseHandle(hEvent1);
CloseHandle(hEvent2);
return 0;
}
void __cdecl producerFun(void* param)
{
while (TRUE) {
WaitForSingleObject(hEvent1, INFINITE);
if (qu.size()
int id = ID++;
printf("生产商品 %d\n", id);
qu.push(id);
Sleep(2000);
}
else
{
printf("仓库已满,阻塞生产线程\n");
ResetEvent(hEvent1);//仓库已满,阻塞生产者线程
}
if (qu.size() > 0)
{
SetEvent(hEvent2);//唤醒消费者线程
}
}
}
void __cdecl consumerFun(void* param)
{
while (TRUE) {
WaitForSingleObject(hEvent2, INFINITE);
if (qu.size() > 0)
{
int id = qu.front();
qu.pop();
printf(" 消费商品 %d\n", id);
Sleep(3000);
}
else
{
printf("仓库已空,阻塞消费线程\n");
ResetEvent(hEvent2);//阻塞消费者线程
}
if (qu.size()
SetEvent(hEvent1);//唤醒生产者线程
}
}
}