首页 > 解决方案 > Proper usage of QThread in loops

问题描述

I'm trying to getting a little bit deeper with the QThread but have the feeling I'm really not using it correctly in loops.

I have some time consuming calculations which I need to run several times. I'm trying with the following (simplified example):

for(int i = 0; i < 100; ++i)
{
    worker *task = new worker();

    connect(task, &worker::finished, this, &controller::calcFinished);
    connect(task, &worker::resultReady, this, &controller::handleResult);
    task->start();
}

The run() function looks like this:

variable = 0;

for(int i = 0; i < 5000; ++i)
{
    for(int j = 0; j < 500; ++j)
    {
        for(int k = 0; k < 500; k++)
        {
            ++variable;
        }
    }
}

emit resultReady(variable);

With this I have a several problem:

I've tried the QThreadPool, which seems to be a solution to the questions I have, but from there I was not able to collect the result of the calculation in the thread. Maybe I missed something with it?

Some additional notes: Currently I'm using the method where I re-implement the run() function. I've tried the moveToThread() method as well, but there I'm even more lost. So if that would be the solution some could try to explain it to me how is that working. I was checking the documentation from Qt: https://doc.qt.io/qt-5/qthread.html But here I have the feeling that even emitting of the 'operate' signal is missing in the example (otherwise why need to connect it?)

Thanks for the answers in advance!

标签: c++qtqthread

解决方案


QtConcurrent::run()Qt Concurrent框架中使用。

extern int aFunction();
QThreadPool pool;
QFuture<int> future = QtConcurrent::run(&pool, aFunction);

然后,您可以从未来对象中检索结果

int result = future.result();

推荐阅读