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"
相关推荐
雨田言炎2 小时前
Qt的常用类QList--序列数据管理
嵌入式硬件·qt
朽棘不雕5 小时前
Qt项目代码解释
开发语言·qt
CVer儿6 小时前
vs2022配置qt
开发语言·qt
kaixin_learn_qt_ing6 小时前
Qt 打开目录多选对话框
qt
lqj_本人14 小时前
WinPcap 鸿蒙 PC 适配全记录:从 NPF 原始抓包到 VPN_TUN 与 libpcap 双通路
qt·华为·harmonyos
Quz17 小时前
QML StackView:三种入栈方式(Item、Component 与 URL)
qt
Quz17 小时前
QML StackView:入栈、出栈、替换与批量操作
qt
老赵的博客20 小时前
c++面试之从虚函数表到Rtti一次性讲清楚
c++·qt
颜颜yan_1 天前
Git Cola 鸿蒙 PC 版适配全记录:从 Qt 桌面工具到 ArkTS 原生应用
git·qt·harmonyos
Lsir10110_1 天前
从按钮“点不动“讲起——深入理解 Qt 信号槽机制
开发语言·qt·信号处理