使用qthread的qt emit的奇怪行为 结构C:公共QObject { Q_对象 公众: C() { qDebug()

使用qthread的qt emit的奇怪行为 结构C:公共QObject { Q_对象 公众: C() { qDebug(),qt,qthread,emit,Qt,Qthread,Emit,这两种方法都在主线程中执行: cl()在主线程中执行,因为它是从主线程调用的,ol()由于主线程中的o而在主线程中执行&QueuedConnection 当您将代码更改为版本(即注释)时,cl2()的执行移动到th线程 struct C : public QObject { Q_OBJECT public: C() { qDebug()<<"C()"; //connect(this,SIGNAL(cs()),this,SL

这两种方法都在主线程中执行:
cl()
在主线程中执行,因为它是从主线程调用的,
ol()
由于主线程中的
o
而在主线程中执行&
QueuedConnection

当您将代码更改为版本(即注释)时,
cl2()
的执行移动到
th
线程

struct C : public QObject
{
    Q_OBJECT

public:

    C()
    {
        qDebug()<<"C()";

        //connect(this,SIGNAL(cs()),this,SLOT(cl2()),Qt::QueuedConnection);
    }

    ~C(){qDebug()<<"~C()";}

signals:

    void cs();

public slots:

    void cl()
    {
        //it seems this signal will be emited only when the following loop finished
        //the output is :
        // cl2 ......... cl2 obj ..........obj
        // which means that the sub-thread not work simultaneously with the main thread
        // but if i move the bold line to cl2 function  and add 
        // connect(this,SIGNAL(cs()),this,SLOT(cl2()),Qt::QueuedConnection); to constructor
        // its output will be:
        // cl2 ... cl2 ..obj ..obj... cl2...obj...... 
        // which mean that main thread and sub-thread work concurrently.
        // any idea about it?  

        emit cs(); 
        for (int i=0;i<=1000000;++i)
            qDebug()<<"cl2";
    }

    void cl2()
    {
        //for (int i=0;i<=1000000;++i)
        //    qDebug()<<"cl2";
    }
};

struct Obj : public QObject
{
    Q_OBJECT

public:

    Obj(){qDebug()<<"Obj()";}

    ~Obj(){qDebug()<<"~Obj()";}

public slots:

    void ol()
    {
        for (int i=0;i<=10000000;++i)
            qDebug()<<"Obj";
    }
};

int main(int argc,char* argv[])
{
        QApplication app(argc, argv);

        QThread th;

        C * c=new C;

        Obj *o=new Obj;

        c->moveToThread(&th);

        th.start();

        QObject::connect(c,SIGNAL(cs()),o,SLOT(ol()),Qt::QueuedConnection);

        c->cl();

        QTimer::singleShot(300,&app,SLOT(quit()));

        app.exec();
}