How to make the main thread wait for one of the functions of the child thread to end
I use qthread. Because I really don't know how to give a runnable example, I can only briefly describe it. A child thread will be generated when the main thread is running. This child thread will call A (), B (), C () in succession A value will be returned in B (). The main thread needs this value to continue the following calculation. However, it will waste a lot of time to wait for the end of the whole sub thread. I'm not familiar with threads. I hope I can get an answer.
Solution 1:
Mmm there is a bunch of ways of doing it... I'll show you one... probably bad one, but it is one way of doing it...
Read comments & ask questions when lost.
class mainWindow : public QWidget {
Q_OBJECT
QLabel *mMyLabel;
Q_SIGNALS:
void sHandleProcessedData(const QString &data);
private Q_SLOTS:
inline void handleProcessedData(const QString &data) {
mMyLabel->setText(data);
/// This should be your Main Thread.
qDebug() << "We are in thread : " << QThread::currentThread() << QThread::currentThread()->objectName();
};
public:
mainWindow() {
/// Take a note of your thread
qDebug() << "We are in thread : " << QThread::currentThread() << QThread::currentThread()->objectName();
/*!
* Simple example gui to show processed data
*/
auto lay = new QGridLayout(this);
mMyLabel = new QLabel("I Will be replaced by worker thread data!");
lay->addWidget(mMyLabel);
auto btn = new QPushButton("Do Processing");
connect(btn, &QPushButton::released, this, &mainWindow::spawnProcess);
lay->addWidget(btn);
/*!
* Lazy thread message hockup using signals
*/
connect(this, &mainWindow::sHandleProcessedData, this, &mainWindow::handleProcessedData, Qt::QueuedConnection); // We want to FORCE queued connection as to not execute this function in worker thread context. We have to be in MAIN thread.
}
inline void spawnProcess() {
/*!
* I'll Use QtConcurrent coz I'm lazy. With Lambda using this as capture.
*/
QtConcurrent::run(this, [this]() {
/// Lots and lots of processing in another thread.
/// Once processing is done, we will send the result via signal to main app.
qDebug() << "We are in thread : " << QThread::currentThread() << QThread::currentThread()->objectName();
Q_EMIT sHandleProcessedData("Some Magical data"); // This will change the Label text to this.
});
}
};