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;
}