QThreads永远不会退出,尽管排放已完成

时间:2016-03-22 13:51:55

标签: c++ multithreading qt qt5

以下情景:

如果用户按下" StartMeasure"按钮我启动一个新的工作线程,以避免在GUI中阻止行为!

我再次开始n个用于硬件通信的新线程(由于速度原因需要并行流) - >发送/接收内容并评估响应。

主题模型:

enter image description here

问题是n工作线程(用于HW通信)永远不会退出!

简化代码:

void Tool::on_btn_StartMeasure()
{
    TestExecution *testExecution = new TestExecution();
    QThread *workerThread = new QThread();

    connect(workerThread, &QThread::started, testExecution, &TestExecution::DoTest);
    connect(testExecution, &TestExecution::Finished, workerThread, &QThread::quit);

    testExecution->moveToThread(workerThread);
    workerThread->start();
}

TestExecution Class

class TestExecution : public QObject
{
    Q_OBJECT

    public:
        void DoTest();

    signals:
         void Finished();

};

void TestExecution::DoTest()
{
    std::vector<std::shared_ptr<TestFlow>> objects;
    std::vector<QThreads*> workerThreads;        

    for(int n=0; n<numberOfDevices; n++)
    {
        workerThreads.push_back(new QThread());
        objects.push_back(std::make_shared<TestFlow>());
        connect(workerThreads.back(), &QThread::started, objects.back().get(), &TestFlow::DoWork);
        connect(objects.back().get(), &TestFlow::Finished, workerThreads.back(), &QThread::quit);

        objects.back()->moveToThread(workerThreads.back());
        workerThreads.back()->start;
    }    

    // wait for worker threads to finish
    for(auto it=workerThreads.begin(); it!=workerThreads.end(); it++)
    {
        (*it)->wait(30); // wait a maximum of 30s -> for testing
    }

    // do something with the result <--- NEVER REACHED

    emit Finished();
}

TestFlow类

class TestFlow : public QObject
{
    Q_OBJECT

    public:
        void DoWork();

    signals:
         void Finished();

};

void TestFlow::DoWork()
{
    // do something
    emit Finished(); <-- REACHED
}

如果我在TestFlow中到达完成信号,他会步入qobject_impl.h方法QSlotObjectBase::call(Object *r, void **a)并停在那里。如果我等待足够长的时间(30秒的线程超时),workerThreads会终止!

这里有什么问题或遗漏?

感谢您的帮助!

更新

qDebug的输出(只有1个工作线程)

Tool::on_btn_StartMeasure(), currentThread QThread(0x601b08), object thread QThread(0x601b08)
TestExecution::DoTest(), currentThread QThread(0x388bf68) , object thread QThread(0x388bf68)
TestFlow::DoWork(), currentThread QThread(0x3958690) , object thread QThread(0x3958690)

对我好吗?!

0 个答案:

没有答案