Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"QObject::startTimer: timers cannot be started from another thread" without timers && CPU consumption

Tags:

c++

qt

I created a multithreaded application in Qt (4.7.2). Only the main thread has an event loop.

The issue is that sometimes I get the following warning in the console:

QObject::startTimer: timers cannot be started from another thread

After this happens, the app consumes 100% of CPU (I have a single core CPU). It seems, that the main thread consumes all of the CPU's resources. The program does not freeze, and everything still works.

When I stop the program in the debugger, I do not see my code in the call stack.

The problem is that I'm not using (explicitly, anyway) timers at all.

What could it be connected with? I know, that question is very common, but I can't even understand, what piece of code to show.

like image 448
Lol4t0 Avatar asked Jul 18 '11 12:07

Lol4t0


1 Answers

Thanks, to @vrince I've fixed the problem. I used signals/slots mechanism + Qt::QueuedConnection to communicate with GUI

For example, if I need to set text of QLabel from worker thread, I can make in my worker thread signal

void textChanged(QString);

then I connect this signal to the slot of QLabel using Qt::QueuedConnection

connect(worker, SIGNAL(textChanged(QString)), label, SLOT(setText(QString), Qt::QueuedConnection);

If I want to execute setText synchronously, I can use Qt::BlockingQueuedConnection

now in my worker thread I just emit signal:

emit textChanged(newText);

Also, it is possible to use QMetaObject functions to avoid signals and slots:

metaObject->invokeMethod(label, "setText", Qt::QueuedConnection, Q_ARG(QString, text));
like image 158
Lol4t0 Avatar answered Nov 15 '22 16:11

Lol4t0