[英]How to make the main thread wait for one of the functions of the child thread to end
我使用qthread。 因為實在不知道怎么給出一個可運行的例子,只能簡單描述一下。 主線程運行時會產生一個子線程。 這個子線程會依次調用A()、B()、C(),B()中會返回一個值。 主線程需要這個值來繼續下面的計算。 但是,等待整個子線程結束會浪費很多時間。 我對線程不熟悉。 我希望我能得到答案。
嗯,有很多方法……我給你看一個……可能很糟糕,但這是一種方法……
閱讀評論並在迷路時提出問題。
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.
});
}
};
您可能想使用 Qt 的 Signals & Slots 機制:
在子線程 object 中定義一個信號。 使用Qt::QueuedConnection將此信號連接到主線程 object 中的插槽。 在 B() 結束時,以 B() 的返回值作為信號參數發出信號。 當子線程 object 發出的信號被主線程事件循環處理時,將調用主線程 object 中的槽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.