Unless you have left out critical code, you do not seem to be ensuring thread safety. You need a QWaitCondition and a QMutex. Check out the mandelbrot example.
Here is the relevant code for a safe construction of a worker thread.
{
public:
{
abort = false;
start(LowPriority);
}
~JobThread()
{
mutex.lock();
abort = true;
condition.wakeOne();
mutex.unlock();
wait();
}
void addJob(Job job)
{
this->jobs << job;
condition.wakeOne();
}
void run()
{
while(!abort) {
if (!jobs.isEmpty())
{
condition.wait(&mutex);
continue;
}
Job job = jobs.takeFirst();
lock.unlock();
while (!abort) {
// do heavy computing
process(job);
emit progress(...);
}
lock.relock();
}
}
private:
mutable bool abort;
QList<Job> jobs;
};
class JobThread : public QThread
{
public:
JobThread(QObject *parent)
: QThread(parent)
{
abort = false;
start(LowPriority);
}
~JobThread()
{
mutex.lock();
abort = true;
condition.wakeOne();
mutex.unlock();
wait();
}
void addJob(Job job)
{
QMutexLocker locker(&mutex);
this->jobs << job;
condition.wakeOne();
}
void run()
{
QMutexLocker lock(&mutex);
while(!abort) {
if (!jobs.isEmpty())
{
condition.wait(&mutex);
continue;
}
Job job = jobs.takeFirst();
lock.unlock();
while (!abort) {
// do heavy computing
process(job);
emit progress(...);
}
lock.relock();
}
}
private:
mutable bool abort;
QMutex mutex;
QWaitCondition condition;
QList<Job> jobs;
};
To copy to clipboard, switch view to plain text mode
I would also consider using QtConcurrent.
Bookmarks