在不同的内核上运行 QThreads
Run QThreads on different cores
在8 cores
MBP上使用Mac OS 10.9
QT 5.1
和C++
我做了一个小程序,运行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()
,则实际上不会为您创建线程,并且您希望确切地看到您所看到的串行执行。
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在C应用程序中运行C++(带有STL)函数
- 运行程序时出现问题
- 控制允许动态运行c++的并发操作数
- 在不同的内核上运行 QThreads