سؤال

Using Mac OS 10.9 QT 5.1 and C++ on a 8 cores MBP

I made a little program which run 8 different QThread. The execution seems to be linear and not parallel as it should : the 1st thread starts with run(), and the 2nd one starts only when the first finished the run() routine...

On the activity monitor I should see a value higher than 100% for the cpu usage if the QThread was executing in the same time but it never happens.

Does someone know how to run QThread on different cores?

main.cpp

#include <QCoreApplication>
#include <QDebug>
#include "MyThread.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyThread t0 (0);
    MyThread t1 (1);
    MyThread t2 (2);

    t0.run();
    t1.run();
    t2.run();


    return 0;
}

MyThread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>

class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(int threadNumber, QObject *parent = 0);
    void run();

private:
    int _threadNumber;

};

#endif // MYTHREAD_H

MyThread.cpp

#include <QDebug>
#include "MyThread.h"


MyThread::MyThread(int threadNumber, QObject *parent)
{
    _threadNumber = threadNumber;
}

void MyThread::run()
{
    qDebug() << "Hi, I'm" << _threadNumber  << "named" << currentThreadId() << "and I start";
    // Some long task
    qDebug() << "Hi, I'm" << _threadNumber <<"and I'm done";

}
هل كانت مفيدة؟

المحلول

Change your code from invoking .run() to

t0.start();
t1.start();
t2.start();

The idea is QThread's start() method does the necessary to setup the thread, and then it invokes your overridden run() on the thread. If you just invoke run() directly yourself, nothing actually creates the thread for you and you'd expect to see exactly the serial execution you're seeing.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top