c++ 无限的生产者消费者

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fx_odyssey/article/details/78888264

有这样一种情况,要无限的生产,伴随着无限的消费。类似生产者消费者模式。水平太次,一直没有弄出来。后来才恍然大悟,原来答案近在眼前。这是一个演示无限生产消费的例子。没有解释,不是高冷,实在是怕说错,想要学习多线程,请参考morewindows大神的多线程系列

#include <stdio.h>
#include <process.h>
#include <Windows.h>
#include <stdlib.h>
#include <conio.h>
#include <queue>
using namespace std;
queue<int> qi;
char text;
int nPCount = 0;
CRITICAL_SECTION g_cs;
unsigned int __stdcall ProducerThreadFun(PVOID pM)
{
    while (1)
    {
        EnterCriticalSection(&g_cs);
        if (_kbhit())
        {
            text = _getch();
            if (text != 't')
            {
                nPCount++;
                qi.push(nPCount);
                printf(" 进队%d\n", nPCount);
            }
            if (text == 't')
            {
                printf("生产者完成任务,线程结束运行。。。\n");
                exit(0);
                break;
            }
        }
        LeaveCriticalSection(&g_cs);
    }
    return 0;
}
unsigned int __stdcall ConsumerThreadFun(PVOID pM)
{
    while(1)
    {
        EnterCriticalSection(&g_cs);
        if (!qi.empty())
        {            
            printf("  \t出队%d\n", qi.front());
            qi.pop();
        }
        LeaveCriticalSection(&g_cs);
    }
    return 0;
}
int main()
{
    InitializeCriticalSection(&g_cs);
    const int ThreadNum = 2;
    HANDLE hThread[ThreadNum];
    hThread[0] = (HANDLE)_beginthreadex(NULL, 0, ProducerThreadFun, NULL, 0, NULL);
    hThread[1] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);
    WaitForMultipleObjects(ThreadNum, hThread, TRUE, INFINITE);
    for(int i = 0; i < ThreadNum; i++)
        CloseHandle(hThread[i]);
    DeleteCriticalSection(&g_cs);
    system("pause");
    return 0;
}
喜不自胜,仅记录,以表开心。里边几处多余的,先不改了。。。哈哈哈


猜你喜欢

转载自blog.csdn.net/fx_odyssey/article/details/78888264
今日推荐