[Interest] QTimer and QThread

Dmitry Kozlov gnitry at mail.ru
Thu Aug 1 05:24:52 CEST 2013


On 01.08.2013 12:36, Mandeep Sandhu wrote:
> 1) From QTimer documentation:
>
>         */Qt uses the timer's/**/thread affinity
>         <https://qt-project.org/doc/qt-4.8/qobject.html#thread>/**/to
>         determine which thread will emit the/**/timeout()
>         <https://qt-project.org/doc/qt-4.8/qtimer.html#timeout>/**/signal.
>         Because of this, you must start and stop the timer in its
>         thread; it is not possible to start a timer from another thread./*
>
>     But you starts timer from source thread. Timer will not starts.
>
>
> From the same doc (just the prior sentence):
>
> "In multithreaded applications, you can use QTimer in any thread that 
> has an event loop. To start an event loop from a non-GUI thread, use 
> QThread::exec()."
>
> I think the OP's code satisfies the requirements. He has an event loop 
> running in the QThread and is calling start() from that thread.
>
>     You should use something like:
>
>
>     screenshot_qtmr=newQTimer;//(this);
>     screenshot_qtmr->setInterval(freq*1000);
>
>     screenshot_qtmr->moveToThread(this);
>     qDebug() << connect(this, SIGNAL(started()),screenshot_qtmr, SLOT(start()));
>
>     qDebug()  <<  connect(screenshot_qtmr,  SIGNAL(timeout()),  this,  SLOT(on_screenshot_timeout()));
>
>     qDebug()  <<  connect(this,  SIGNAL(kill_tmr()),  screenshot_qtmr,  SLOT(stop()));
>
>     //screenshot_qtmr->start(freq*1000); // do not do it
>
>
>
>     2) In you sample on_screenshot_timeout will be executed in main
>     thread, maybe you need change
>
>     connect(screenshot_qtmr,  SIGNAL(timeout()),  this,  SLOT(on_screenshot_timeout()));
>     to
>     connect(screenshot_qtmr,  SIGNAL(timeout()),  this,  SLOT(on_screenshot_timeout()), Qt::DirectConnection);
>     ?
>
>
> DirectConnection will only change in which thread context the slot 
> gets called, but it should still get called at least (provided the 
> timer is running)
>
> -mandeep
>


Oh this is run() method..., I'm sorry. Was inattentive... And 
moveToThread() is not necessary here... Sorry.

I see possible problems:
1) state_analizer_tmr_id is not set -> exec() isn't called
2) timer's interval value is incorrect
3) main thread is blocked -> slot isn't called (because of queued 
connection)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20130801/2aec6b33/attachment.html>


More information about the Interest mailing list