[wx-dev] Re: wxString(s.c_str()) thread safety (was Re: wxString
threadsafe)
Hajo Kirchhoff
mailinglists at hajo-kirchhoff.de
Fri May 2 01:25:34 PDT 2008
Sorry, I did not follow this thread too closely, so I don't know what
the consensus is on this one. But I'd like to pass on my experience. I
was the original thread starter, after I spent days searching for a very
elusive segfault/crash.
The problem is much worse than I initially thought. It's not just
AddPendingEvent, which is causing problems. I have to change the entire
interface between threads.
Example: My worker thread uses wxSockets to connect to a remote server.
Naturally I use a wxString to pass the remote server hostname from the
main GUI thread to the worker thread. Bad idea! wxStrings cannot be
shared between threads.
And so on. I will now eliminate wxString from the interfaces of all
worker thread classes, so that they either accept a TCHAR* or are using
std::basic_string<TCHAR>. The alternative would be a meticuously code
reading to examine every occurrence of wxString, determining if it might
be shared between threads. Just one copy, even a temporary one, is
enough to corrupt the heap.
For my next project I will stay away from wxString in worker threads
entirely. Which really defeats the purpose of wxString.
Seeing the code and considering the fact that the crashes occur only on
multicore systems, atomic increments/decrements will probably solve the
problem.
I would strongly argue that the performance penalty occurred for
wxString copy operations is neglible.
In situation where performance is relevant, one shouldn't use wxString
copies anyway, atomically incremented or not, but rather use pointers or
references. In all other situations, having a few microseconds more is
just the price to pay for multithreaded programming.
I consider a string to be a very basic object, like wxPoint, int and
others. Certainly less complex than wxList or queue. It is then very
misleading and irritating that wxString should not be thread safe at all
- even with proper thread synchronisation objects in place - , when I
can share complex objects such as lists between threads.
Modifying the code to use .c_str() or TCHAR* in all places where a
string would be shared otherwise is not an option IMHO, since these
places are very hard to spot. Making all wxString instances private for
example does not help, since the boundaries do not run along class
interfaces.
So my strong wish for wxWidgets 2.9 and up would be to have a thread
safe wxString class by default. In todays multicore/multithread world I
would consider this to be a critical bug rather than a design feature.
Lets have a wxUSE_ATOMIC_STRING_COUNTING 0 for those wishing to keep the
current mechanism, but make thread safety the default.
Thank you for listening
Best regards
Hajo
More information about the wx-dev
mailing list