views:

484

answers:

2

What's the best/proper method to collect log messages from multiple threads and have them all be displayed using a window? (while the threads are running).

I am currently trying to redirect stdout (cout) in to a wxTextCtrl but failing miserably when attempting to do so over multiple threads. Any help would be appreciated.

+1  A: 

In what way is it failing? I'm not familiar with the wxTextCtrl, but unless it has built in synchronization (ie. its thread safe) that could be a big issue. The simplest way to protect a single resource like this is via a named 'mutex'. The following example is what you can do in each thread to make sure that only one accesses this resource (the output window) at a time.

// In each thread's initialization:
HANDLE mutexHandle = CreateMutex(0,FALSE,"__my_protecting_mutex__");


// Whenever you use the debug output:

WaitForSingleObject(mutexHandle, /* Timeout if you like. */ 0xFFFFFFFF );
// Do our printing here.
ReleaseMutex(mutexHandle);


// In each thread's cleanup:
CloseHandle(mutexHandle);

So this basically guarantees that only one thread can be in between the wait and the release. Now if your issue is actually routing to the wxTextCtrl, I would need some more details.

Edit: I just realized that what I posted is Windows specific, and maybe you aren't on windows! If you aren't I don't have experience with other platform's synchronization methods, but boost has some generic libraries which are not platform specific.

DeusAduro
wxWidgets has a built in, cross-platform wxMutex classhttp://docs.wxwidgets.org/stable/wx_wxmutex.html
GRB
Synchronization is only part of it. It's a bad idea to write directly to a wxTextCtrl from different threads, a much better way is to add log messages to a thread-safe (synchronized) data structure, and have the main GUI thread do the logging to the text control from the queued data. wxWidgets trunk has this now, see the other answer.
mghie
+2  A: 

Logging has had a few major updates recently in the wxWidgets trunk, you can read about them here. One of them is to add support for logging from threads other than the main thread.

SteveL