生产者消费者同步问题c++|操作系统

发布于 2021-07-10  27 次阅读


这是生产者消费者同步问题的c++程序,如果对其中函数有不理解的可以看我另一篇博客进程相关函数汇总解释,对照着看,可能方便你理解

在这里插入图片描述
#include <Windows.h>
#include <iostream>
#define SIZE_OF_BUFFER 10
using namespace std;
typedef HANDLE semaphore;

//
#define P(S) WaitForSingleObject(S,INFINITE)
#define V(S) ReleaseSemaphore(S,1,NULL)

int g_buffer[10];
int in = 0;
int out = 0;
int ProduceID = 1000;
int CousumeID;

DWORD WINAPI Producer(LPVOID lpPara);
DWORD WINAPI Consumer(LPVOID lpPara);
semaphore g_hEmptySemaphore = CreateSemaphore(NULL, 10, 10, NULL);
semaphore g_hFullSemaphore = CreateSemaphore(NULL, 0, 10, NULL);
semaphore g_hMutex = CreateSemaphore(NULL, 1, 1, NULL);

void print();
int x = 0;
int y = 0;

void main()
{
    HANDLE hThread1;
    HANDLE hThread2;
    hThread1 = CreateThread(NULL, 0, Producer, NULL, 0, NULL);
    hThread2 = CreateThread(NULL, 0, Consumer, NULL, 0, NULL);
    while (1)
    {
        WaitForSingleObject(hThread1, INFINITE);
        WaitForSingleObject(hThread2, INFINITE);
    }
}

int color(int num)
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), num);
    return 0;
}

void gotoxy(int x, int y)
{
    HANDLE hCon;
    hCon = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD Pos;
    Pos.X = x;
    Pos.Y = y;
    SetConsoleCursorPosition(hCon, Pos);
}

void print()
{
    for (int i = 0; i < SIZE_OF_BUFFER; i++)
    {
        gotoxy(40, i + 5);
        if (i == in)
            color(1);
        else if (i == out)
            color(4);
        else
            color(7);
        std::cout << i << ":" << g_buffer[i];
    }
}


//生产一个产品
void Produce()
{
    ++ProduceID;
}

//把新生产的产品放入缓冲区
void Append()
{
    color(7);
    g_buffer[in] = ProduceID;
    if (y == 25)
    {
        y = 0;
        system("cls");
    }
    gotoxy(x, y++);
    std::cout << "生产者生产了" << g_buffer[in];
    std::cout << std::endl;
    print();
    in = (in + 1) % SIZE_OF_BUFFER;
}

//取出一个产品
void Take()
{
    color(7);
    CousumeID = g_buffer[out];
    if (y == 25)
    {
        y = 0;
        system("cls");
    }

    gotoxy(x, y++);
    std::cout << "\t\t消费者消费了" << CousumeID;
    g_buffer[out] = 1000;
    print();
    out = (out + 1) % SIZE_OF_BUFFER;
}


DWORD WINAPI Producer(LPVOID lpPara)
{
    while (1)
    {
        P(g_hEmptySemaphore);
        P(g_hMutex);
        Produce();
        Append();
        Sleep(1500);
        V(g_hMutex);
        V(g_hFullSemaphore);
    }
    return 0;
}

DWORD WINAPI Consumer(LPVOID lpPara)
{
    while (1)
    {
        P(g_hFullSemaphore);
        P(g_hMutex);
        Take();
        Sleep(1500);
        V(g_hMutex);
        V(g_hEmptySemaphore);
    }
    return 0;
}