欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Win32多线程之单生产者,但消费者,单个缓冲区的同步问题

程序员文章站 2022-05-04 17:10:12
...

以下是在下对多线程中的单生产者,但消费者,单个缓冲区问题的理解,Win32实现,如有不对之处还望大神指教,在下感激不尽!话休絮烦,用代码说话:

#include<stdio.h>
#include<windows.h>
#include<process.h>

int buf;//缓冲区

HANDLE hProduceEvent;
HANDLE hConsumeEvent;

unsigned int __stdcall producer(void* pVoid)
{
    int i = 1;
    while (true)
    {
        WaitForSingleObject(hProduceEvent,INFINITE);
        buf = i;
        Sleep(100);//模拟生产时间
        printf("生产者生产了一件产品,其值为%d\n",buf);
        i++;
        ResetEvent(hProduceEvent);
        SetEvent(hConsumeEvent);//唤醒消费者

    }
    return 0;
}

unsigned int __stdcall consumer(void* pVoid)
{
    while (true)
    {
        WaitForSingleObject(hConsumeEvent, INFINITE);
        printf("消费者消费了产品%d\n\n", buf);
        Sleep(100);//模拟消费时间
        ResetEvent(hConsumeEvent);
        SetEvent(hProduceEvent);//唤醒生产者
    }
    return 0;
}

void main()
{
    hProduceEvent = CreateEvent(NULL,TRUE,TRUE,NULL);//生产者初始有信号
    hConsumeEvent = CreateEvent(NULL, TRUE, FALSE, NULL);//消费者初始无信号
    HANDLE hProducer = (HANDLE)_beginthreadex(nullptr, 0, producer,nullptr,0,nullptr);
    HANDLE hConsumer = (HANDLE)_beginthreadex(nullptr, 0, consumer, nullptr, 0, nullptr);
    WaitForSingleObject(hProducer,INFINITE);
    WaitForSingleObject(hConsumer, INFINITE);
    CloseHandle(hProducer);
    CloseHandle(hConsumer);
    CloseHandle(hProduceEvent);
    CloseHandle(hConsumeEvent);
    system("pause");
}

运行结果如下:
Win32多线程之单生产者,但消费者,单个缓冲区的同步问题

相关标签: 线程同步