在不同的核心上运行QThreads

时间:2013-12-26 21:49:00

标签: c++ qt qthread

Mac OS 10.9 MBP上使用QT 5.1 C++8 cores

我做了一个小程序,运行8个不同的QThread。执行似乎是线性的并且不应该是并行的:第一个线程以run()开头,第二个线程仅在第一个完成run()例程时才开始......

在活动监视器上,如果QThread在同一时间执行但是它从未发生过,我应该看到cpu使用率高于100%的值。

有人知道如何在不同的核心上运行QThread吗?

的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";

}

1 个答案:

答案 0 :(得分:4)

将您的代码从调用.run()更改为

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

这个想法是QThread的start()方法做了设置线程所必需的,然后它在线程上调用被覆盖的run()。如果您只是直接调用run(),那么实际上并没有为您创建该线程,您希望看到您正在看到的串行执行。

相关问题