I don't get it. I want to start a thread that periodically executes a function using a timer.
{
start();
}
void Thread::run()
{
connect(&t, SIGNAL(timeout()), this, SLOT(tick()));
t.start(100);
//t.moveToThread(this);
exec();
}
void Thread::tick()
{
qDebug() << currentThreadId() << "tick()";
}
{
Thread thread;
...
};
ThreadTest
::ThreadTest(QWidget *parent
){
qDebug
() <<
QThread::currentThreadId() <<
"is the main thread.";
}
Thread::Thread(QObject *parent) : QThread(parent)
{
start();
}
void Thread::run()
{
QTimer t;
connect(&t, SIGNAL(timeout()), this, SLOT(tick()));
t.start(100);
//t.moveToThread(this);
exec();
}
void Thread::tick()
{
qDebug() << currentThreadId() << "tick()";
}
class ThreadTest : public QWidget
{
Thread thread;
...
};
ThreadTest::ThreadTest(QWidget *parent)
: QWidget(parent)
{
qDebug() << QThread::currentThreadId() << "is the main thread.";
}
To copy to clipboard, switch view to plain text mode
And the output I get is:
0x12b8 is the main thread.
0x12b8 tick()
0x12b8 tick()
0x12b8 tick()
0x12b8 tick()
...
0x12b8 is the main thread.
0x12b8 tick()
0x12b8 tick()
0x12b8 tick()
0x12b8 tick()
...
To copy to clipboard, switch view to plain text mode
Obviously, the timer is still running on the main thread. Using the moveToThread() doesn't make a difference. What's not right about this?
Changing the timer to an infinite loop with sleep() works though.
void Thread::run()
{
forever
{
tick();
sleep(1);
}
}
void Thread::run()
{
forever
{
tick();
sleep(1);
}
}
To copy to clipboard, switch view to plain text mode
0xa04 is the main thread.
0xfa0 tick()
0xfa0 tick()
0xfa0 tick()
...
0xa04 is the main thread.
0xfa0 tick()
0xfa0 tick()
0xfa0 tick()
...
To copy to clipboard, switch view to plain text mode
Bookmarks