【问题标题】:How should I design a program to read from multiple streams of data?我应该如何设计一个程序来读取多个数据流?
【发布时间】:2011-01-23 01:30:59
【问题描述】:

我正在编写一个程序,它使用两个不同的数据流来执行某些计算。我目前的代码设置如下:

//pseudo c++

class Calculator
{
    //Stream is a class which contains a queue which has new messages added to it
    Stream a, b;

    bool BothQueuesHaveItems() { return !a.IsEmpty() && !b.IsEmpty(); }
    void PerformCalc() { /*Do domething with the first items in a and b*/ }

};


unsigned ThreadFunction(void *stop_event)
{
    Calculator calculator;

    while(WaitForSingleObject(stop_event) == WAIT_OBJECT_0)
    {
        if(calculator.BothQueuesHaveItems())
        {
            calculator.PerformCalc();
        }
        Sleep(5);
    }
}

int main()
{
    Event stop_event = CreateEvent(...);
    CreateThread(ThreadFunction, &stop_event, ...);

    //wait for user enter command to stop processing
    SetEvent(stop_event);
}

这似乎不是一个很好的设计(特别是 ThreadFunction 中的连续循环,无论队列中是否有新项目),但我不确定如何改进它。任何建议,将不胜感激。

【问题讨论】:

    标签: c++ windows multithreading winapi


    【解决方案1】:

    不要使用IsEmpty,而是从流中读取一个字符。读取将阻塞,直到字符准备好(至少在 *nix 中,不确定 Windows)。

    类似

    pair <char,char> nextItems() { return make_pair(a.readChar(), b.readChar()); }
    

    应该可以正常工作。

    唯一的麻烦是实现你的stop_eventnextItems 将永远等待,因此您需要将读取代码放在单独的线程中并让 stop_event 直接退出进程。

    【讨论】:

      【解决方案2】:

      我要么使用 Win32 重叠(异步)读取,要么为每个流创建一个线程以执行同步、阻塞读取。

      【讨论】:

        猜你喜欢
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多