我使用qthread。因為實在不知道怎么給出一個可運行的例子,只能簡單描述一下。主執行緒運行時會產生一個子執行緒。這個子執行緒會依次呼叫A()、B()、C(),B()中會回傳一個值。主執行緒需要這個值來繼續下面的計算。但是,等待整個子執行緒結束會浪費很多時間。我對執行緒不熟悉。我希望我能得到答案。
uj5u.com熱心網友回復:
嗯,有很多方法……我給你看一個……可能很糟糕,但這是一種方法……
閱讀評論并在迷路時提出問題。
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.
});
}
};
uj5u.com熱心網友回復:
您可能想使用 Qt 的 Signals & Slots 機制:
- 信號和插槽
- 跨執行緒的信號和槽
在您的子執行緒物件中定義一個信號。使用Qt::QueuedConnection將此信號連接到主執行緒物件中的插槽。在 B() 結束時,以 B() 的回傳值作為信號引數發出信號。當子執行緒物件發出的信號被主執行緒事件回圈處理時,將呼叫主執行緒物件中的槽。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417437.html
標籤:
