CommandThread - thread processing events

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
yaro
Earned a small fee
Earned a small fee
Posts: 11
Joined: Sun Feb 04, 2007 2:10 pm

CommandThread - thread processing events

Post by yaro »

I have written a class CommandThread that can process wxWidgets events in the context of the thread. Event handling works with standard macros and Connect.

The core of the solution was to make

Code: Select all

class ThreadEvtHandler : public wxEvtHandler
and override AddPendingEvent so it doesn't add the event handler to the global list of event handlers (since we want event handler to be executed from the worker thread not the main thread).

also ProcessThreadEvent had to be overridden since AddPendingEvent isn't virtual. ProcessThreadEvent isn't used anywhere in the wxWidgets library but can be used by the user.

In constructor we have to create new list so that ProcessPendingEvents doesn't fail.

Code: Select all

m_pendingEvents = new wxList();
ThreadEvtHandler also has 1 semaphore to signal the thread that some data is ready from AddPendingEvent.

Then CommandThread is defined like this:

Code: Select all

class CommandThread : public ThreadEvtHandler, public wxThread
ThreadEvtHandler has to be on the left due to problems with function pointers.

Then Entry() looks like this:

Code: Select all

  while (!TestDestroy())
   {
      m_SemaphoreEvtReady.WaitTimeout(100);
      ProcessPendingEvents();
   }
Problems to be avare of:

1.) ::wxPostEvent cannot be used, as it calls wxEvtHandler::AddPendingEvent and AddPendingEvent isn't virtual :(
Use AddPendingEvent directly.

2.) ProcessEvent() cannot be used directly for synchronous event processing, as the event will be processed in the current thread.
This means event processing chains spanning multiple threads will not work as you might expect.

3.) Note that CommandThread cannot have event handlers for example for button or mouse events from other windows, they have to be in the window they belong to. If you try to create event handler chains (using SetNextHandler) it won't work properly either as it will run into problem 2.) with ProcessEvent().

How it should be used:

- to send events from one thread to another using AddPendingEvent, the advantage over custom processing using simple queues in wxThread is that you can use event macros and Connect() if you use CommandThread
Attachments
commandthread.zip
(1.91 KiB) Downloaded 195 times
Post Reply