多线程之多生产者,多消费者,多缓冲区问题解决(Win32API实现)

/*
    多线程之多生产者,多消费者,多缓冲区问题
*/
#include<stdio.h>
#include<windows.h>
#include<process.h>

#define BUF_SIZE 10

int buffer[BUF_SIZE];   //缓冲区
int in=0, out=0;

HANDLE hEmpty, hFull;
CRITICAL_SECTION produce_cs, consume_cs;//分别用于生产者与生产者之间,消费者与消费者之间的互斥

unsigned int __stdcall producer(void* pVoid)
{
    int production = 0;
    int id = (int)pVoid;
    while (true)
    {
        WaitForSingleObject(hEmpty, INFINITE);  //执行P操作
        EnterCriticalSection(&produce_cs);
        Sleep(1000);    //模拟生产时间
        production++;   //生产一件产品
        printf("生产者%d生产了产品%d\n", id,production);
        buffer[in] = production;
        in = (in+1) % BUF_SIZE;
        LeaveCriticalSection(&produce_cs);
        ReleaseSemaphore(hFull, 1, NULL);   //执行V操作
    }
    return 0;
}

unsigned int __stdcall consumer(void* pVoid)
{
    int production;
    int id = (int)pVoid;
    while (true)
    {
        WaitForSingleObject(hFull, INFINITE);   //执行P操作
        EnterCriticalSection(&consume_cs);
        production = buffer[out];
        out = (out + 1) % BUF_SIZE;
        printf("消费者%d消费了产品%d\n", id,production);
        Sleep(1000);    //模拟消费时间
        LeaveCriticalSection(&consume_cs);
        ReleaseSemaphore(hEmpty, 1, NULL);  //执行V操作
    }
    return 0;
}

void main()
{

    hEmpty = CreateSemaphore(NULL,BUF_SIZE,BUF_SIZE,NULL);
    hFull = CreateSemaphore(NULL, 0, BUF_SIZE, NULL);
    InitializeCriticalSection(&produce_cs);
    InitializeCriticalSection(&consume_cs);
    HANDLE hProducer1 = (HANDLE)_beginthreadex(nullptr, 0, producer, (void*)1, 0,nullptr);
    HANDLE hProducer2 = (HANDLE)_beginthreadex(nullptr, 0, producer, (void*)2, 0, nullptr);
    HANDLE hProducer3 = (HANDLE)_beginthreadex(nullptr, 0, producer, (void*)3, 0, nullptr);
    HANDLE hConsumer1 = (HANDLE)_beginthreadex(nullptr, 0, consumer, (void*)1, 0, nullptr);
    HANDLE hConsumer2 = (HANDLE)_beginthreadex(nullptr, 0, consumer, (void*)2, 0, nullptr);
    WaitForSingleObject(hProducer1, INFINITE);
    WaitForSingleObject(hProducer2, INFINITE);
    WaitForSingleObject(hProducer3, INFINITE);
    WaitForSingleObject(hConsumer1, INFINITE);
    WaitForSingleObject(hConsumer2, INFINITE);
    CloseHandle(hProducer1);
    CloseHandle(hProducer2);
    CloseHandle(hProducer3);
    CloseHandle(hConsumer1);
    CloseHandle(hConsumer2);
    CloseHandle(hEmpty);
    CloseHandle(hFull);
    DeleteCriticalSection(&produce_cs);
    DeleteCriticalSection(&consume_cs);
    system("pause");
}

猜你喜欢

转载自blog.csdn.net/csdn_gddf102384398/article/details/81772889