[wx-dev] Re: wxString(s.c_str()) thread safety (was Re:
wxString threadsafe)
Robert Roebling
robert at roebling.de
Fri May 2 02:53:28 PDT 2008
Hajo Kirchhoff wrote:
> 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.
Without using c_str() or pretty much just removing reference counting
the problem will probably not go away, unless I'm mistaken.
> 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.
which are not reference counted.
> 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.
It should be rather easy to add a compilation option to disable ref
counting, I'm no longer sure how much value using atomic reference
counting has.
Robert
More information about the wx-dev
mailing list