[wx-dev] Re: wxString(s.c_str()) thread safety (was Re: wxString threadsafe)

Hajo Kirchhoff mailinglists at hajo-kirchhoff.de
Fri May 2 06:29:15 PDT 2008


Hi Robert,
> happen as reference counting is not useless) the correct
> way to have a wxString in the interface would probably
> be something like this
> 
> wxString MyWorkerThread::Foo()
> {
>    wxMutexLocker lock( m_stringMutex );
>    return m_mystring.Clone();
> }

this would let me retrieve a string from the thread. What about the 
other way round?

void MyWorkerThread::SetTargetIP(const TCHAR *ip)
{
   wxMutexLocker lock(m_stringMutex);
   m_myTargetIp=ip;
}

Would this work when SetTargetIP is called by the main thread?

I think not. m_myTargetIp might be a wxString object created by the 
worker thread from another wxString object still owned by the worker 
thread. So even if the mutex locker protects m_myTargetIp, the shared 
string object behind it is not protected.

If at the same time the worker thread modifies the string object shared 
with m_myTargetIp, we'll end up with a heap corruption again.

Here's the code:

void MyWorkerThread::PrepareSomething()
{
   wxMutexLocker lock(m_stringMutex);
   m_myTargetIp=m_myOtherTargetIp;
}

void MyWorkerThread::DoSomething()
{
   // both strings share the same string object
   m_myOtherTargetIp=wxString::Format(something);
}

Since 'm_myOtherTargetIp' is not shared between threads, it is not 
protected by a mutex.

If SetTargetIp() and DoSomething() happen to run concurrently, we get a 
heap corruption.



But actually I think even if it would, it is just to problematic as it 
is. It's way to easy to forget something.

If atomic counting does not solve the problem, then lets do away with 
reference counting. I'd rather have a working program than a fast one.

Regards

Hajo



More information about the wx-dev mailing list