在不同的内核上运行 QThreads

Run QThreads on different cores

本文关键字:运行 QThreads 内核      更新时间:2023-10-16

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

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

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

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

主.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

我的线程.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";
}

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

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

这个想法是 QThread 的 start() 方法执行设置线程所必需的操作,然后它在线程上调用您覆盖的run()。 如果您只是自己直接调用run(),则实际上不会为您创建线程,并且您希望确切地看到您所看到的串行执行。