0

I've created to create a listener class that will call methods such as on_left_mouse_released on a controller object. It works fine, and now I am trying to have it run in another thread using boost::thread. However, I seem to be doing something wrong. I am new to multithreading, so this could easily be a simple error.

Here are selected portions from the listener class:

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();
}

In my main function, if I create a Listener object named listener, then say "listener();" both of the couts occur with the appropriate events. However, if I use "boost::thread listen (boost::ref(listener));" instead, nothing happens.

Does anyone see why this is?

Kvothe
  • 467
  • 4
  • 13
  • Is `ReadConsoleInput()` safe to call on a non-UI thread? A quick look of the documentation doesn't say either way, but that is the common gotcha with you start out writing multi-threaded software for Windows (or indeed MacOSX & iOS). – marko Aug 10 '12 at 22:40
  • This sounds likely. What other kinds of things are limited like this? Could you recommend a link that talks about this? – Kvothe Aug 10 '12 at 23:17

1 Answers1

0

Most likely you've started the thread and forgot to wait for the thread to exit before you exit your test program. Add a

listen.join();

at the end of your test program.

Torsten Robitzki
  • 3,041
  • 1
  • 21
  • 35
  • That did the trick. Thanks! Can you recommend any good multithreading tutorials? – Kvothe Aug 13 '12 at 23:10
  • @Kvothe "Programming with POSIX Threads" from David Buttenhof is a very good book to get the basics, even when it only covers pthread. boost thread is quit similar to posix threads. And it's very entertaining ;-) – Torsten Robitzki Aug 14 '12 at 05:47