qt+Linux+arm多核CPU 亲和性

复制代码
#include <QCoreApplication>
#include <QThread>
#include <pthread.h>
#include <sched.h>
#include <iostream>

void setThreadAffinity(int coreId) {
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(coreId, &cpuset);// 设置线程执行在cpu编号为cpu的核上

    // 获取当前线程ID
    pthread_t thread = pthread_self();
    // 设置当前线程的亲和性
    int result = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
    if (result != 0) {
        qWarning() << "Failed to set thread affinity, error code:" << result;
    } else {
        qDebug() << "Thread successfully bound to CPU" << cpu;
    }
}

class WorkerThread : public QThread {
public:
    void run() override {
        setThreadAffinity(1);  // 绑定到 CPU 核心 1
        std::cout << "Thread is running on core 1" << std::endl;
        // 模拟一些工作
        for (int i = 0; i < 1000000; ++i);
    }
};

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    WorkerThread worker;
    worker.start();

    return a.exec();
}

目前大部分的CPU都支持多核,QT的主线程默认运行在第一个CPU的核心中,当执行复杂而耗时的任务是,程序界面有可能会出现卡顿,而其它的核心又没用到,白白浪费了资源。

qt的QThead类本身是没有设置cpu亲和性的接口的,需要自己封装一个接口将QT线程运行到指定的cpu核心中。

前提是要确定cpu是支持多核的

相关推荐
Web3探索者5 小时前
可视化服务器管理和传统命令行区别是什么?新手教程:Linux 运维到底该用图形界面还是 SSH 命令行?
linux·ssh
zylyehuo7 小时前
Linux系统中网线与USB网络共享冲突
linux
Quz11 小时前
QML Hello World 入门示例
qt
Sokach10151 天前
Linux Shell 脚本从零到能用:一个新手的一天学习总结
linux
AlfredZhao2 天前
Docker 容器时区不对,`timedatectl` 不存在怎么办?
linux·timezone
zzzzzz3103 天前
9K Star 炸裂开源!这个 C 语言写的代码知识图谱,把 Linux 内核索引压缩到了 3 分钟
linux·服务器·sql
xcyxiner3 天前
DicomViewer (dcmtk读取dcm文件)5
qt
XIAOHEZIcode3 天前
Linux系统鼠标偏移常见原因以及修复方案
linux·运维·游戏
xcyxiner4 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner4 天前
DicomViewer (添加模型类)3
qt