PDA

View Full Version : Call method of Object in different Thread



Qiieha
26th July 2012, 11:36
Hi, a little Question...

I have several Objects, and each of this objects live in its own thread. (moveToThread)

Further I have a pool, which has a QList<Object*>, which holds the objects. The Pool lives in the mainthread.

Is it right, that if I call a method of an object within my pool-class, the method is processed in the object's thread? And Is it right, that I have to lock the member method with QMutex?

thank u

Santosh Reddy
26th July 2012, 12:36
Is it right, that if I call a method of an object within my pool-class, the method is processed in the object's thread?
No. the method is processed(executed) in the calling thread (main thread) context.


And Is it right, that I have to lock the member method with QMutex?
You can use QMutex (for non-QObject based objects), but it will not work for any QObject based object's member functions.

yeye_olive
26th July 2012, 12:48
No, a method (more generally any function) is always executed in the same thread that called it. This has nothing to do with them being methods of QObjects who happen to have a notion of thread affinity.

However, Qt contains some features allowing a programmer to easily trigger the execution of a method of a QObject in the thread controlling this QObject (which may be distinct from the current thread) provided this thread runs an event loop. One such way is to use signal-slot connections. Another way (which may be simpler in your case) is to use QMetaObject::invokeMethod().

In any case I strongly recommend you read the docs on signals/slots across threads and QObject's thread affinity.

I do not understand what you mean by "lock the member method with QMutex". All I can say is that QMutex is useful when you need to serialize access to a resource shared among sevaral threads.

Qiieha
26th July 2012, 13:14
Thank u for your replies!
Now the issue is clear for me.