Here is how thread work's (AFAIK, please correct me if I'm wrong), using Your example:
Thread *myThread = new Thread();
Thread *myThread = new Thread();
To copy to clipboard, switch view to plain text mode
call a constructor:
Thread::Thread()
{
}
Thread::Thread()
{
}
To copy to clipboard, switch view to plain text mode
Then thread is on the stack, so you can fire it up like so:
myThread->start();
myThread->start();
To copy to clipboard, switch view to plain text mode
and in the thread this protected run() is always called, as manual said "starting point for the thread":
void Thread::run()
{
exec();
}
void Thread::run()
{
exec();
}
To copy to clipboard, switch view to plain text mode
Here You want to start exec()ution of the thread. Calling exec() tell thread to enter event loop. Thread run until exit()/quit() is called, so In Your case forever. Exec() is int because it is similar to main function "int main()" in normal program, it returns int at the end of execution to let you know if there was error int != 0.
int Thread::exec()
{
while(1)
{
emit(testSignal("hello world!"));
sleep(1);
}
}
int Thread::exec()
{
while(1)
{
emit(testSignal("hello world!"));
sleep(1);
}
}
To copy to clipboard, switch view to plain text mode
Your thread runs forever, because no exit() or quit() is called, and the signal is emitted each 1s.
So to sum it up, run() is called after mythread->start(), and exec() enters event loop for the thread.
You could do something like this also:
void Thread::run()
{
myfirstfunction();
mysecoundfunction();
exec();
}
void Thread:: myfirstfunction()
{
//do some heavy duty stuff / blocking gui operation
}
void Thread:: mysecoundfunction()
{
//proces data
exit();
}
void Thread::run()
{
myfirstfunction();
mysecoundfunction();
exec();
}
void Thread:: myfirstfunction()
{
//do some heavy duty stuff / blocking gui operation
}
void Thread:: mysecoundfunction()
{
//proces data
exit();
}
To copy to clipboard, switch view to plain text mode
And, depending on what is in myfirs/secound function, the execution flow is first then secound and end of the thread. Also note that if You don't call exit() / quit() inside thread, thread runs "forever" (actually main app don't know if thread execution ended or not ), and using delete mythread() yields error "QThread: Destroyed while thread is still running" or similar. Depending what you are doing in the thread, or on what point You call delete application crash or simply runs but only output error. Also always delete after new because this is mem leek, and depending on Your implementation or data inside thread you can run out of the memory.
I hope this helps to understand how thread works, and again this information is as I see the thread, maybe there is some mistake so please point them out.
Best regards.
Bookmarks