如何在c++中使用winapi事件解决生产者-消费者问题? [英] How to solve Producer-Consumer using winapi events in c++?

查看:23
本文介绍了如何在c++中使用winapi事件解决生产者-消费者问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用原始同步对象 - 事件在 C++ 中解决生产者-消费者问题,我已经写了这段代码

I need to solve Producer-Consumer problem in c++ using primitive synchronization objects - events, I already wrote this code

static int g_x = 0;
HANDLE hEvent1;

HANDLE aThread[2];
DWORD ThreadID;

//tread 1
void Producer()
{
    for (int i = 0; i < 100; ++i)
    {
        WaitForSingleObject(hEvent1, INFINITE);
        g_x = i;
        SetEvent(hEvent1);
    }
}
//thread 2
void Consumer()
{
    for (;;)
    {
        WaitForSingleObject(hEvent1, INFINITE);
        SetEvent(hEvent1);
    }
}

int createthreads() {
    hEvent1 = CreateEvent(NULL, FALSE, TRUE, NULL);

    // Create worker threads
    aThread[0] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)Producer, NULL,  0, &ThreadID);
    aThread[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Consumer, NULL, 0, &ThreadID);
}
int main() {
    createthreads();
}

此代码无法正常工作:我有无限循环如何修复此代码以获取从 099 的控制台编号?

This code doesn't work correctly: I have Infinite cycle How can I fix this code to get in console numbers from 0 to 99 ?

推荐答案

您需要另一个事件来同步这两个线程.此外,我将两个事件的初始状态设置为 FALSE,并将开始事件发送到 main 上的生产者线程.
通过这种方式,您可以控制流程的启动时间和方式.

You need another event to syncronize this two threads. Also I set the initial state of two events to FALSE, and I send a start event to the producer thread on the main.
This way you can control when and how the process is started.

和 Offtopic 一样,createthreads 必须返回一个值.

And Offtopic, createthreads must return a value.

static int g_x = 0;
HANDLE hEvent1;
HANDLE hEvent2;

HANDLE aThread[2];
DWORD ThreadID;

//tread 1
void Producer()
{
    for (int i = 0; i < 100; ++i)
    {
        WaitForSingleObject(hEvent1, INFINITE);
        g_x = i;
        SetEvent(hEvent2);
    }
}
//thread 2
void Consumer()
{
    for (;;)
    {
        WaitForSingleObject(hEvent2, INFINITE);
        SetEvent(hEvent1);
    }
}

int createthreads() {
    hEvent1 = CreateEvent(NULL, FALSE, FALSE, NULL);
    hEvent2 = CreateEvent(NULL, FALSE, FALSE, NULL);

    // Create worker threads
    aThread[0] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)Producer, NULL,  0, &ThreadID);
    aThread[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Consumer, NULL, 0, &ThreadID);
    return 0;
}
int main() {
    createthreads();
    SetEvent(hEvent1);
}

这篇关于如何在c++中使用winapi事件解决生产者-消费者问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆