c++qtqthreadqt4.8

Cross-platform issues or what is the alternative to QtConcurrent :: run?


I need to run the function asynchronously in a separate thread, I used QtConcurrent :: run everything was fine when I tested windows, but as soon as I ran the same code on linux, it started to work synchronously. Using qt4.8 and c++98 :c

Testable code:

void myRunFunction(QString name)
{
    for(int i = 0; i <= 1000; i++)
        qDebug() << name << " " << i << "from" << QThread::currentThread();
}

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

    QFuture<void> t1 = QtConcurrent::run(myRunFunction, QString("A"));
    QFuture<void> t2 = QtConcurrent::run(myRunFunction, QString("B"));
    QFuture<void> t3 = QtConcurrent::run(myRunFunction, QString("C"));

    t1.waitForFinished();
    t2.waitForFinished();
    t3.waitForFinished();

    return a.exec();
}

What I get in the console:

"A" 0 from QThread (0x11a78f8, name = "Thread (pooled)")
...
"A" 1000 from QThread (0x11a78f8, name = "Thread (pooled)")
after
"B" 0 from QThread (0x11a78f8, name = "Thread (pooled)")
...
"B" 1000 from QThread (0x11a78f8, name = "Thread (pooled)")
etc

Tell me how to fix this, or what else can you try? i wanted to try QtConcurrent::run(QThreadPool *pool, Function function, ...) but qt4.8 doesn't have it


Solution

  • Based on the comments it appears that the number of threads in the global QThreadPool instance may be limited, by default, to a single thread due to constraints imposed on the VM.

    To counter that you can simply set the thread count explicitly using...

    QThreadPool::globalInstance()->setMaxThreadCount(4);