Qt主线程把数据发给子线程,主线程会阻塞吗


演示:

javascript 复制代码
#include <QCoreApplication>
#include <QThread>
#include <QObject>
#include <QDebug>

// 子线程类
class Worker : public QObject {
    Q_OBJECT
public slots:
    void processData(int data) {
        qDebug() << "Processing data in thread:" << QThread::currentThread();
        // 模拟耗时操作
        QThread::sleep(2);
        qDebug() << "Finished processing data:" << data;
    }
};

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // 创建子线程对象
    QThread workerThread;
    Worker worker;

    // 将worker对象移动到子线程
    worker.moveToThread(&workerThread);

    // 连接信号和槽
    QObject::connect(&workerThread, &QThread::started, [&worker]() {
        for (int i = 0; i < 5; ++i) {
            emit worker.processData(i);
            QThread::sleep(1); // 模拟主线程的其他工作
        }
    });

    // 启动子线程
    workerThread.start();

    // 主线程继续执行其他任务
    for (int i = 0; i < 5; ++i) {
        qDebug() << "Main thread working...";
        QThread::sleep(1); // 模拟主线程的其他工作
    }

    // 等待子线程完成
    workerThread.quit();
    workerThread.wait();

    return a.exec();
}

#include "main.moc"
相关推荐
look ahead to7 小时前
关于PYQT qt designer的网格布局 单控件占多行的处理
开发语言·qt·pyqt
Lution Young9 小时前
Qt隐式共享产生的问题
开发语言·qt
少控科技11 小时前
QT进阶日记009
开发语言·qt
CodeCraft Studio11 小时前
从框架到体验:Qt + Qtitan 构建制造业嵌入式UI整体解决方案
开发语言·qt·ui·gui·嵌入式开发·hmi·制造业嵌入式ui
深蓝海拓11 小时前
PyQt5/PySide6的moveToThread:移动到线程
笔记·python·qt·学习·pyqt
少控科技11 小时前
QT高阶日记007
开发语言·qt
余衫马12 小时前
Qt for Python:PySide6 入门指南(中篇)
开发语言·c++·python·qt
njsgcs12 小时前
python qt做ai透明对话框
人工智能·python·qt
少控科技13 小时前
QT高阶日记5
开发语言·qt
少控科技13 小时前
QT高阶日记008
开发语言·qt