In order for quit to work the thread will need to run its event loop.
That is what the QThread::run() base implementation does. If one overwrites run() then one can still start the event loop by calling exec().
void MyThread::run()
{
// do some setup
exec(); // runs until quit is called
}
void MyThread::run()
{
// do some setup
exec(); // runs until quit is called
}
To copy to clipboard, switch view to plain text mode
I would stronlgy advise against calling terminate(), it can leave the program in state that it can not recover from.
I am not really sure what your full use case is but calling a function regularily can easily be done without threads, e.g. using QTimer.
DataBrain
::DataBrain(Source source,
QObject *parent
) : QObject(parent
){
switch (source.principal)
{
case SourceInternet:
switch (source.internet)
{
case SourceYahoo:
connect(timer,SIGNAL(timeout()),this,SLOT(slotUpdateYahoo()));
break;
case SourceGoogle:
connect(time,SIGNAL(timeout()),this,SLOT(slotUpdateGoogle()));
D_TODO("DataBrain::run() | SourceGoogle");
break;
default:
M_BUG_OCCURANCE("DataBrain::DataBrain() | SourceInternet");
break;
}
break;
case SourceRealTime:
D_TODO("DataBrain::DataBrain() | SourceRealTime");
break;
case SourceLocal:
M_BUG_OCCURANCE("DataBrain::DataBrain() | currentSource == SourceLocal");
break;
}
timer->start(250);
}
DataBrain::DataBrain(Source source, QObject *parent) : QObject(parent)
{
QTimer *timer = new QTimer(this);
switch (source.principal)
{
case SourceInternet:
switch (source.internet)
{
case SourceYahoo:
connect(timer,SIGNAL(timeout()),this,SLOT(slotUpdateYahoo()));
break;
case SourceGoogle:
connect(time,SIGNAL(timeout()),this,SLOT(slotUpdateGoogle()));
D_TODO("DataBrain::run() | SourceGoogle");
break;
default:
M_BUG_OCCURANCE("DataBrain::DataBrain() | SourceInternet");
break;
}
break;
case SourceRealTime:
D_TODO("DataBrain::DataBrain() | SourceRealTime");
break;
case SourceLocal:
M_BUG_OCCURANCE("DataBrain::DataBrain() | currentSource == SourceLocal");
break;
}
timer->start(250);
}
To copy to clipboard, switch view to plain text mode
Or putting that into a DataBrain::start() method, etc.
And since we are already talking about threads, when exactly it's appropriate to use QSemaphore instead of QMutex/QMutexLocker and vice-versa?
A binary semaphore, i.e. a QSemaphore which only ever has two values (0 and 1), is basically equivalent with QMutex. However, since there is no QMutexLocker equivalent, I would recommend using QMutex when the use case is to protect a generic critical section against concurrent access.
The semaphore becomes interesting when it is being used with values n > 1, waiting for n threads to finish, or using it to enforce a resource usage limit, etc.
Cheers,
_
Bookmarks