0
class A:public QObject
{

    Q_OBJECT

    public slots:

    void f() {
        while(1) {
            qDebug()<<"f"<<thread()<<thread()->isRunning();
            sleep(1);
            **QMetaObject::invokeMethod(thread(), "quit", Qt::QueuedConnection);**
        }
    }

    public slots:

    void g() { qDebug() << "g"; }
};


int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QThread th;
    A a;
    a.moveToThread(&th);
    th.start();
    a.f();// running in main thread
    return app.exec();
}

输出总是:

f QThread(0xbfdef1e0) 真

f QThread(0xbfdef1e0) 真

f QThread(0xbfdef1e0) 真

我想知道为什么 qthread 永远不会退出,因为我确实使用“QMetaObject::invokeMethod(thread(), "quit", Qt::QueuedConnection);" 在循环内调用了退出

谢谢

4

2 回答 2

0
int main(int argc, char *argv[])

{

    QCoreApplication app(argc, argv);

    QThread th;

    A a;

    a.moveToThread(&th);

    th.moveToThread(&th); <------it works ,after I add this line

    th.start();

    a.f();// running in main thread

    return app.exec();

}
于 2011-12-14T03:32:30.887 回答
0

您的线程永远不会退出,因为它处于一个紧密的无限循环中。如果您从不屈服于 Qt 偶数循环,它就无法执行任何排队的操作。Qt 不能神奇地停止代码的执行以运行事件循环。

如果您将以下行添加到循环中,您会看到线程确实停止了:

QCoreApplication::processEvents();

因为您仍然必须屈服于 Qt 的事件循环,以便它能够将您的信号传递给另一个线程。

于 2011-12-13T04:31:20.277 回答