Solved How to ensure thread's run function executes first
-
Hi ,
I have the below code where I am using threads started signal to ensure run function of the clientThread executes first and then any other function. All initialization are done in the run function and if any other function (serverConnect fn as below) executes first it creates issues.
But using logs I see that 1 in 10 times run function of clientThread executes after serverConnect().Thank you,
void Base::drpThreadStarted() { /* Once DRP thread is started , start the client thread. */ connect(clientThread,SIGNAL(started()),this,SLOT(clientThreadStarted())); clientThread->start(); } void Base::clientThreadStarted() { /* Connect to the notification server. */ clientThread->serverConnect(); /* Connect to the message queue in watchdog. */ clientThread->watchdogConnect(); }
-
using threads started signal
At a guess, I would assume the signal indicates the thread has been started, but not that it has therefore already executed some instruction, even if it's the first one! So every so often it doesn't.
If you need to be sure of the order of instructions across threads, you need some synchronising (mutex, semaphore, etc.) mechanism.
No?
-
-
Base is QMainwindow class and it should not be the issue because we are serializing the flow using started() signal and also drpThread and clientThreads are threads only as below:
Base::Base(QWidget *parent) : QMainWindow(parent, Qt::FramelessWindowHint) { #if MAIN_THREAD_DEBUG qDebug() << "Base CTOR called"; #endif setStyleSheet("background-color:gray"); setAutoFillBackground( true ); drpThread = new DRPThread; clientThread = new ClientThread; presenTimer = NULL; nextGuiTimer = NULL; } class DRPThread : public QThread { Q_OBJECT signals: ... private: void run(); Base *base; public: private slots: void rcvMsg(); //Recieve message from client thread void threadFinished(); void initDataTimerHit(); }; class ClientThread : public QThread { Q_OBJECT signals: ... private: void run(); QTimer *ka_timer; QTimer *conn_retry_timer; public: .... void serverConnect(); void watchdogConnect(); private slots: ..... void threadFinished(); private: ; };
-
Hi,
From the looks of it, you are going to try to access a GUI element from DRPThread which is wrong.
That noted, if you want to trigger things one after the other then you should signal precisely when you're done with the initialisation phase.
-
Read the links I posted above and also this document: http://doc.qt.io/qt-5/thread-basics.html
Base is QMainwindow class and it should not be the issue because we are serializing the flow using started() signal
You think you do, but you're not. Both of those two slots are queued through the main thread's event loop, and also the slots in the
QThread
subclasses (unless invoked directly) are going to be executed in the main thread. -
Ok Thanks.