This is objectA which subclass QThread
void run()
{
while (continue)
emit query();
}
void work(int input, bool workdone)
{
// work hard here
if (workdone) { continue = false; }
}
This is some code in main object
{
ObjectA A* = new ObjectA(this);
connect(A, SIGNAL(query()), this, SLOT(handleQuery()));
objectA.start();
}
void handleQuery()
{
A.work(interger, allJobDONE);
}
OK, I don't know how to name the question. Basically, it is just "will this code work?" If yes, how would be the code sequence?
Let me explain my question. ObjectA is a thread. It is going to query information from time to time by emitting a query signal. When the query signal is grubbed by the main code, the main code decide whether there is job so as to send the job to ObjectA by calling work()
function.
If this code works, both the run()
and the work()
function in the same object work at the same time. Is this possible?
There are few problems:
ObjectA::run()
blocks the event loop of the thread;A.work()
is called from the wrong thread;A
.Instead of blocking while
loop in run()
it is better to use timer. However, in that case the thread event loop should be executed (that it done in the default implementation of QThread::run()
. So some other member slot should be used for that task to start, for example:
void ObjectA::doLoop()
{
emit query();
QTimer::singleShot(0, this, SLOT(doLoop()));
}
That function should be called when the thread is started, for example it can be done by connection in ObjectA
constructor:
connect(this, SIGNAL(started()), this, SLOT(doLoop()));
Even better to keep private pointer QTimer*
to be able to stop that timer from work()
or to have some other control. Note that in that case QTimer
object should be in the same thread as ObjectA
.
Normally the ObjectA::work()
function should be triggerd by some signal from handleQuery()
. The event loop of ObjectA
will catch that signal and the work()
will be started in ObjectA
thread.