PDA

View Full Version : QThread not running in different thread



lauwe
27th February 2011, 22:29
I am trying to create a thread with an object inside it that does some work periodically (using a QTimer). My idea was to subclass QThread and have all communication as well as the timed event run through the event-loop. But with my current example, everything seems to still run in the same thread.

This is the thread-class.


class thread : public QThread
{
Q_OBJECT

private:
QTimer *_timer;

public:
void run(void);

public slots:
void startTimer(int timeout);
void _timeout(void);

};

void
thread::run(void) {
/* start the event-loop */
exec();
}

void
thread::startTimer(int timeout) {
if(!_timer)
_timer = new QTimer();

QObject::connect(_timer, SIGNAL(timeout()), this, SLOT(_timeout()));

_timer->setInterval(timeout);
_timer->start();
}

void
threadn::_timeout(void) {
qDebug() << "timeout from" << QThread::currentThreadId();
}


This is what I run from my 'main' thread:


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

thread *t = new thread();

QObject::connect(this, SIGNAL(startTimer(int)), t, SLOT(startTimer(mode,int)), Qt::QueuedConnection);
t->start(QThread::HighestPriority);

qDebug() << "Hello from " << QThread::currentThreadId();

emit startTimer(1000);
}

wysota
27th February 2011, 22:32
http://www.qtcentre.org/search.php?do=process&query=QThread+affinity

lauwe
27th February 2011, 23:02
Thanks for the link!

After reading some more I found that threading in Qt does not work as I thought. The following does seem to work:


/* notice that thread no longer inherits from QThread */
class thread : public QObject
{
Q_OBJECT

private:
QTimer *_timer;

public slots:
void startTimer(int timeout);
void _timeout(void);

};

void
thread::startTimer(int timeout) {
if(!_timer)
_timer = new QTimer();

QObject::connect(_timer, SIGNAL(timeout()), this, SLOT(_timeout()));

_timer->setInterval(timeout);
_timer->start();
}

void
threadn::_timeout(void) {
qDebug() << "timeout from" << QThread::currentThreadId();
}

Now create a QThread object and move the instance of 'thread' to it.


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

thread *t = new thread();
QThread *qthread = new QThread();

QObject::connect(this, SIGNAL(startTimer(int)), t, SLOT(startTimer(mode,int)), Qt::QueuedConnection);
t->moveToThread(qthread);

qthread->start(QThread::HighestPriority);

qDebug() << "Hello from " << QThread::currentThreadId();

emit startTimer(1000);
}