View Full Version : how to create two thread and acess the same data member of the class

19th May 2011, 08:46
all i want two create two thread,by these two thread i want to access member function of the class which are manipulating the data member of the class,how can i access these function by the two different threads in Qt.

please help

thanks with regards:

19th May 2011, 09:33
Why do you think you need two threads?
What is the task you have to achieve?

19th May 2011, 10:11
Same answer as above, only a bit more elaborate since I had already started writing :)

The QThread class could be what you are looking for together with QMutex to ensure serialized access to shared data. Most likely though, you don't want to use threads at all. Contrary to popular belief, threads do not improve performance of your program. They can however make it more responsive by creating the illusion of performing multiple tasks at once. In Qt you have several ways of achieving this without directly using low-level threading primitives. So the question is really; are threads the best solution in this particular case?

Before subclassing QThread and reimplementing QThread::run(), you should consider some other options:

The QtConcurrent API, where the actual threading code is "hidden".
To use a QObject with different thread affinity as a "worker".

QThread *thread = new QThread(this);
Worker* worker = new Worker; // Worker is a QObject subclass
QMetaObject::invokeMethod(worker, "doSomething");

// and eventually worker needs to be destroyed somewhere
delete worker;

...or any of the other suggestions, as outlined here: