QT多线程在run()中emit信号时,槽函数将运行在新线程当中
main.cpp
QCoreApplication a(argc, argv);
//init
ReceClass receClass;
Demo1 demo1;
Demo1 demo2;
qDebug() << QObject::connect(&demo1, &Demo1::sendMsg, &receClass, &ReceClass::receMsg, static_cast<Qt::ConnectionType>(Qt::DirectConnection | Qt::UniqueConnection));
qDebug() << QObject::connect(&demo2, &Demo1::sendMsg, &receClass, &ReceClass::receMsg, static_cast<Qt::ConnectionType>(Qt::DirectConnection | Qt::UniqueConnection));
qDebug()<< QString("mainwindow thread id: %1").arg((int)QThread::currentThreadId());
//run
demo1.setMsg("demo1");
demo2.setMsg("demo2");
demo1.start();
demo2.start();
return a.exec();
demo1.cpp
void Demo1::run()
{
for (int i = 0; i < 10; i++)
{
emit sendMsg(this->msg);
qDebug() <<"SubThread run() thread id:" << (int)this->currentThreadId() << ": emit " << this->msg << "over";
}
qDebug() << "msg: " << this->msg << "over";
}
void Demo1::setMsg(const QString& msg)
{
qDebug() <<"SubThread not run() thread id:" << (int)this->currentThreadId();
this->msg = msg;
}
receClass.cpp
ReceClass::ReceClass(QObject *parent)
: QObject(parent)
{
QString str = QString("ReceClass thread id: %1").arg((int)QThread::currentThreadId());
qDebug() << str;
}
ReceClass::~ReceClass()
{}
void ReceClass::receMsg(QString msg)
{
QString str = QString("slot thread id: %1").arg((int)QThread::currentThreadId());
qDebug() << str << "get mes:" + msg;
QThread::sleep(1);
}