qt6 thread tip1

新的线程必须要使用信号槽机制才能启动。假如一个对象a live在thread b上。那么start thread b后直接调用a里面的函数不能使a运行在b上。正确的做做法是先start thread b。然后用信号槽机制调用a,a就可以运行在thread b上了。如果直接调用a还是会在main thread 上运行。

  	QThread::currentThread()->setObjectName("main thread");
    qInfo()<<"Starting"<<QThread::currentThread();

  	QThread worker;
    worker.setObjectName("Worker Thread");

    Test test;
    test.moveToThread(&worker);
    worker.start();

    test.run();

运行结果:
Starting QThread(0x2995b1464c0, name = “main thread”)
Running QThread(0x2995b1464c0, name = “main thread”)
Finished QThread(0x2995b1464c0, name = “main thread”)
Finished QThread(0x2995b1464c0, name = “main thread”)
仍然在main thread 上运行.
采用信号槽机制启动test.run

	QThread::currentThread()->setObjectName("main thread");
    qInfo()<<"Starting"<<QThread::currentThread();

	QThread worker;
    worker.setObjectName("Worker Thread");

    Test test;
    test.moveToThread(&worker);
    QTimer timer1;
    worker.start();

    timer1.singleShot(10,&test,&Test::run);
    QObject::connect(&worker,&QThread::started,&test,&Test::run);

运行结果:
Starting QThread(0x191017364c0, name = “main thread”)
Finished QThread(0x191017364c0, name = “main thread”)
Running QThread(0x3a155ffaa0, name = “Worker Thread”)
Finished QThread(0x3a155ffaa0, name = “Worker Thread”)
Timeout QThread(0x3a155ffaa0, name = “Worker Thread”)

你可能感兴趣的:(c++,qt)