Most elegant way to call method in an object in another thread
-
I have a simple class:
class MyClass { public: int getWorkResult() { return doSomeWork(); } private: int doSomeWork(); };I want to be able to call
getWorkResult()from every thread of my program. ButdoSomeWork()must always run in the same thread, because of synchronization.
What is the best way? I want callinggetWorkResult()from all the threads be simple as possible. I don't mind that threads may be waiting for a while to the result.My solution so far:
class MyClass : public QObject { Q_OBJECT public: MyClass() { connect(this, &MyClass::getWorkResultSignal, this, &MyClass::getWorkResultSlot, Qt::BlockingQueuedConnection); } int getWorkResult() { int result; emit getWorkResultSignal(&result); return result; } signals: void getWorkResultSignal(int * returnValue); private slots: void getWorkResultSlot(int * returnValue){ &returnValue = doSomeWork(); } private: int doSomeWork(); }Now I can call
getWorkResult()really simply in every thread:int result = myClass->getWorkResult();Is my solution correct? Is there a better solution?
-
You can just do
int getWorkResult() { int result; QMetaObject::invokeMethod(this, &MyClass::doSomeWork, &result); return result; }This will do all the connection plumbing for you.