Qt信号槽跨线程与lambda表达式


Qt Version 5.12.6
话不多说直接上码

test.h

#ifndef TEST_H
#define TEST_H
#include <QObject>

class Test: public QObject{
    Q_OBJECT
public:
signals:
    void test1(const QString& str);
    void test2(const QString& str);
};

#endif // TEST_H

main.cpp

#include <QCoreApplication>
#include <QThreadPool>
#include <QtConcurrent/QtConcurrent>
#include <QThread>
#include <QDebug>
#include "test.h"

inline void printTID(const QString& str="")
{
    qDebug() << QThread::currentThreadId() << str;
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Test* test = nullptr;
    QThreadPool pool;
    printTID(":tmain");
    QtConcurrent::run(&pool, [&test](){
        test = new Test;
        printTID(":t1");
        QEventLoop e;
        QObject::connect(test, &Test::test1, test/*lambda表达式执行在创建该对象的线程中*/,[](const QString& str){
            printTID(":我在t1中执行 " + str);
        });
        QObject::connect(test, &Test::test2/*lambda表达式执行在创建信号发射对象的线程中*/, [](const QString& str){
            printTID(":我在t2或t3中执行" + str);
        });
        e.exec();
    });
    QtConcurrent::run(&pool, [&test](){
        printTID(":t2");
        while(1)
        {
            if(nullptr != test)
            {
                emit test->test1("from t2");
                emit test->test2("from t2");
            }
            QThread::msleep(1000);
        }
    });
    QtConcurrent::run(&pool, [&test](){
        printTID(":t3");
        while(1)
        {
            if(nullptr != test)
            {
                emit test->test1("from t3");
                emit test->test2("from t3");
            }
            QThread::msleep(1000);
        }
    });
    while(1)
    {
        QThread::msleep(1000);
    }
    return 0;
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值