为什么QThread ::完成信号没有发出?

Kir*_*ril 2 c++ concurrency qt multithreading qthread

我创建了自己的TestService,它运行在一个单独的QThread,但MainLoop终止时,QThread::finished信号不会被发出.我看到了一个类似的问题,但问题略有不同,因为OP超载QThread而我只是将我的类移到线程上.

请注意,我不超载QThread课,我只重载QObject基于这个例子:http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation /

这是我的TestService班级:

#include <QObject>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <iostream>

using namespace std;
class TestService: public QObject
{
    Q_OBJECT;
private:
    volatile int _count;
    QWaitCondition _monitor;
    QMutex _mutex;
    QThread* _thread;

public:
    TestService(int numSeconds)
    {
        _count = numSeconds;
        _thread = NULL;
        cout << "TestService()" << endl;
    }

    virtual ~TestService()
    {
        cout << "~TestService()" << endl;
    }

    void Start()
    {
        QMutexLocker locker(&_mutex);
        if(_thread == NULL)
        {
            _thread = new QThread;

            // Move this service to a new thread
            this->moveToThread(_thread);

            // The main loop will be executed when the thread
            // signals that it has started.
            connect(_thread, SIGNAL(started()), this, SLOT(MainLoop()));

            // Make sure that we notify ourselves when the thread
            // is finished in order to correctly clean-up the thread.
            connect(_thread, SIGNAL(finished()), this, SLOT(OnFinished()));

            // The thread will quit when the sercives
            // signals that it's finished.
            connect(this, SIGNAL(Finished()), _thread, SLOT(quit()));

            // The thread will be scheduled for deletion when the 
            // service signals that it's finished
            connect(this, SIGNAL(Finished()), _thread, SLOT(deleteLater()));

            // Start the thread
            _thread->start();
        }
    }

    void Stop()
    {
        _count = 0;
        _monitor.wakeAll();
    }
private slots:
    void MainLoop()
    {
        cout << "MainLoop() Entered" << endl;
        while(_count > 0)
        {
            cout << "T minus " << _count << " seconds." << endl;

            QMutexLocker locker(&_mutex);
            _monitor.wait(&_mutex, 1000);
            _count--;
        }
        cout << "MainLoop() Finished" << endl;
        emit Finished();
    }

    virtual void OnFinished()
    {
        cout << "OnFinished()" << endl;
    }
signals:
    void Finished();
};
Run Code Online (Sandbox Code Playgroud)

这是测试代码:

void ServiceTest()
{
    cout << "Press q to quit." << endl;
    cout << "Press s to start." << endl;
    cout << "Press t to stop." << endl;
    QSharedPointer<TestService> testService(new TestService(10));
    char in = 'a';
    while( in != 'q' )
    {
        switch(tolower(in))
        {
        case 's':
            testService->Start();
            break;
        case 't':
            testService->Stop();
            break;
        default:
            break;
        }
        cin.get(in);
        in = tolower(in);
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    ServiceTest();

    QTimer::singleShot(0, &a, SLOT(quit()));

    return a.exec();
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Press q to quit.
Press s to start.
Press t to stop.
TestService()
s
MainLoop() Entered
T minus 10 seconds.
T minus 9 seconds.
T minus 8 seconds.
t
MainLoop() Finished
q
~TestService()
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释为什么finished不发出我怎么解决它?

Lol*_*4t0 7

信号finished()被发出原因,但你没有抓住它.

这里:

connect(_thread, SIGNAL(finished()), this, SLOT(OnFinished()));
Run Code Online (Sandbox Code Playgroud)

Qt::QueuedConnection因为_threadthis(服务)在不同的线程中使用.

finished()发出时,_thread事件循环已经完成执行,因此信号将不会传送到插槽.

你可以明确使用Qt::DirectConnection.

编辑:

QTherad的工作原理如下:

QThread::start()
{
    emit started();
    run();
    emit finished();
}

QThread::run()
{
     eventloop->exec();
}
Run Code Online (Sandbox Code Playgroud)

因此,在finished发出时,eventloop已经停止执行.当你移动service_thread,服务的事件循环是_thread事件循环.

注意,它QObject本身没有自己的事件循环.事件循环由对话框,线程和应用程序创建.


实际上我会建议你在简单的情况下使用QtConcurent::run,因为你不在新线程中执行实际的事件处理,而只是运行单个函数.

  • 我只是注意到QTCurrent :: run中的示例使用了boost :: bind。**感谢更新的答案**:我仍然感到困惑的是,当您说当发出`finished()`时,`_thread`的事件循环已经完成执行了……我不是试图在_thread事件循环中处理它,而是在TestService事件循环中处理它。**如果我正确理解**,由于服务尚未销毁,因此“ TestService”事件循环应仍处于活动状态。 (2认同)