2012-08-10 30 views
0

我創建了一個用於創建監聽器類的類,該類將調用控制器對象上的on_left_mouse_released等方法。它工作正常,現在我試圖讓它在另一個使用boost :: thread的線程中運行。但是,我似乎做錯了什麼。我是多線程新手,所以這可能很容易成爲一個簡單的錯誤。C++ ReadConsoleInput不能與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(); 
} 

以我的主要功能,如果我創建監聽命名對象監聽器,然後說「監聽器();」 這兩個couts出現與適當的事件。但是,如果我使用「boost :: thread listen(boost :: ref(listener));」相反,沒有任何反應。

有沒有人知道這是爲什麼?

+0

'ReadConsoleInput()'安全地調用非UI線程嗎?快速瀏覽一下文檔並不是這樣說的,但是這是你開始爲Windows編寫多線程軟件(或者確實是MacOSX和iOS)的常見問題。 – marko 2012-08-10 22:40:06

+0

聽起來很可能。還有其他什麼東西是有限的呢?你能推薦一個鏈接來談論這個嗎? – Kvothe 2012-08-10 23:17:19

回答

0

很可能您已經啓動了線程,並且在退出測試程序之前忘記等待線程退出。添加一個

listen.join(); 

在您的測試程序結束。

+0

這個伎倆。謝謝!你能推薦一些好的多線程教程嗎? – Kvothe 2012-08-13 23:10:37

+0

@Kvothe David Buttenhof的「使用POSIX線程編程」是一本很好的基礎知識的書,即使它只涵蓋pthread。 boost線程退出類似於posix線程。這是非常有趣的;-) – 2012-08-14 05:47:53

相關問題