PDA

View Full Version : Question about atomic operation and Qt's data sharing.



The Storm
22nd August 2010, 20:02
Lets say I have this sample code:



class MyThead : public QThread
{
public:
MyThead() {};
~MyThread {};

QString getTheString() const { return m_someString; }

protected:
void run()
{
// Do stuff with m_someString....
}

private:
QString m_someString;
}


If for example I call getTheString() method using other thread context will I get crash or something nasty if I do not synchronize m_someString with mutex? I had read about the reentrant and atomic reference counter in Qt but I'm still not sure if I get it right.

On my project I have created an implicitly shared class using the QSharedData technique and I have lots of members that are mixed primitive types and Qt types. The big question here is can I share copy instances of my class without the need of mutex or other type locking?

ecanela
22nd August 2010, 20:26
The big question here is can I share copy instances of my class without the need of mutex or other type locking?

Atomic operation are useful when implement a implicitly shared classes.
When you need share copy instances of any class between difernet threads you need use a mutex or similar classes. to sincronize the access to instances

yakin
22nd August 2010, 20:48
Calling getTheString() would not lead into undefined behavior.

The Qt documentations says the following:


Qt uses an optimization called implicit sharing for many of its value class, notably QImage and QString. Beginning with Qt 4, implicit shared classes can safely be copied across threads, like any other value classes. They are fully reentrant. The implicit sharing is really implicit.

In many people's minds, implicit sharing and multithreading are incompatible concepts, because of the way the reference counting is typically done. Qt, however, uses atomic reference counting to ensure the integrity of the shared data, avoiding potential corruption of the reference counter.

Greetz Yakin

The Storm
22nd August 2010, 21:19
Oh, how I missed that... Thanks a lot. :)

yakin
22nd August 2010, 21:26
You are welcome:) The Qt docs are so wide and that part was really hidden.

franz
23rd August 2010, 06:16
Do note that if you manipulate m_someString in the run thread in several places, you can get undefined behavior: The contents of the string may be odd. The best way to tackle this in my view is to


void ThreadThingy:run()
{
QString theString = m_someString;
// perform operations on theString
m_someString = theString;
}