C++ ReadConsoleInput 不适用于 boost::thread

C++ ReadConsoleInput not working with boost::thread

本文关键字:thread boost 适用于 ReadConsoleInput 不适用 C++      更新时间:2023-10-16

>我创建了一个侦听器类,该侦听器类将在控制器对象上调用on_left_mouse_released等方法。它工作正常,现在我正在尝试使用 boost::thread 让它在另一个线程中运行。但是,我似乎做错了什么。我是多线程的新手,所以这很容易成为一个简单的错误。

以下是侦听器类中的选定部分:

void Listener::listen()
{
keepListening = true;
while(keepListening)
{
    if(timerEnabled)
    {
        this->CheckForTimerEvent();
        if( !PendingMouseOrKeyEvents()) //readconsoleinput is blocking
            continue;
    }
    if(!keepListening) //could have been changed in a timer event
        break;
    if(!mouseEnabled && !keyboardEnabled)
        continue;
    ReadConsoleInput(hIn, &InRec, 1, &NumRead);

    //see http://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx
    //for more information on InRec and its submembers
    if(mouseEnabled &&InRec.EventType == MOUSE_EVENT)
    {
        this->ProcessMouseEvent(InRec.Event.MouseEvent);
        cout << "here";
    }
    else if(keyboardEnabled && InRec.EventType == KEY_EVENT)
    {
        this->ProcessKeyEvent(InRec.Event.KeyEvent);
                    cout << "here";
    }
}
}
void Listener::operator()()
{
    listen();
}

在我的主函数中,如果我创建一个名为 listener 的 Listener 对象,则说"listener();"这两个 cout 都与适当的事件一起发生。但是,如果我使用 "boost::thread listen (boost::ref(listener));",则什么都不会发生。

有人明白这是为什么吗?

很可能您已经启动了线程,但在退出测试程序之前忘记等待线程退出。添加一个

listen.join();

在测试程序结束时。