Win32信号量实现生产者消费者模型

来源:互联网 发布:互联网进入大数据时代 编辑:程序博客网 时间:2024/05/28 23:20

转自:http://blog.csdn.net/webscaler/article/details/6775957

生产者消费者模型简介

        1.如果共享的buffer中有空位,则生产者生产产品,放到空位中;

        2.如果共享的buffer中有产品,则消费者消费产品;


使用win32简单实现 多生产者/多消费者 模型如下


#include <Windows.h>#include <process.h>#include <iostream>using namespace std;HANDLE hProducter;HANDLE hConsumer;int g_in = 0; // 初始生产产品的放置位置int g_out = 0; // 初始消费产品的读取位置const int MAX_NUM = 100;int g_empty = MAX_NUM; // 初始空位数量int g_full = 0;  // 初始产品数量int g_products[MAX_NUM];DWORD WINAPI Productor( LPVOID pParameter){int* pNo = static_cast<int*>(pParameter);while(1){WaitForSingleObject(hProducter, INFINITE);if(g_empty > 0){--g_empty;g_in %= MAX_NUM;g_products[g_in] = g_in;printf("produce id %d pos %d value %d\n", *pNo, g_in, g_products[g_in]);++g_in;++g_full;}ReleaseSemaphore(hProducter, 1, NULL);Sleep(1000);}return 1;}DWORD WINAPI Consumer( LPVOID pParameter){int* pNo = static_cast<int*>(pParameter);while(1){WaitForSingleObject(hConsumer, INFINITE);if(g_full > 0){--g_full;g_out %= MAX_NUM;printf("consume id %d pos %d value %d\n", *pNo, g_out, g_products[g_out]);++g_out;++g_empty;}ReleaseSemaphore(hConsumer, 1, NULL);Sleep(1000);}return 1;}int main(){hProducter = CreateSemaphore(NULL, 1, 1, NULL);hConsumer = CreateSemaphore(NULL, 1, 1, NULL);int ProductorThreadIds[3];int ConsumerThreadIds[3];for(int i = 0; i < 3; ++i){ConsumerThreadIds[i] = i+1;CreateThread(NULL, 0, Consumer, &ConsumerThreadIds[i], NULL, NULL);}for(int i = 0; i < 3; ++i){ProductorThreadIds[i] = i+1;CreateThread(NULL, 0, Productor, &ProductorThreadIds[i], NULL, NULL);}Sleep(10000);return 0;};