繁体   English   中英

如何让主线程等待子线程的功能之一结束

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM