繁体   English   中英

在不同的核心上运行QThreads

[英]Run QThreads on different cores

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

我做了一个小程序,运行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";

}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM