linux线程设置cpu亲和性与调度方式及优先级

2023-05-16

cpus_set.c


#include "cpus_set.h"

int get_cpu_nums()
{
    return sysconf(_SC_NPROCESSORS_CONF);
}
int set_cpus_mask(int* cpus_arr, int nums, cpu_set_t *mask)
{
    CPU_ZERO(mask);
    if (nums > get_cpu_nums())
    {
        printf("%s:%d nums must less then cpu nums total\n", __FUNCTION__, __LINE__);
        return -1;
    }

    for (int i = 0; i < nums; i++)
    {
        if (cpus_arr[i] > (get_cpu_nums() - 1) || cpus_arr[i] < 0)
        {
            printf("cpus_arr[%d]: %d\n",i,cpus_arr[i]);
            printf("%s:%d cpus_arr error\n", __FUNCTION__, __LINE__);
            return -1;
        }
        CPU_SET(cpus_arr[i], mask); //将CPU号加入到mask集合
    }
    //printf("set_cpus_mask success\n");
    return 0;
}
int del_cpu_mask(int cpu_num, cpu_set_t *mask)
{
    if (!CPU_ISSET(cpu_num, mask))
    {
        printf("%s:%d cpu_num does not exist in mask\n", __FUNCTION__, __LINE__);
        return -1;
    }
    CPU_CLR(cpu_num, mask);
    return 0;
}
int bind_pthread_cpu_cores(cpu_set_t *mask, pthread_t pid)
{
    int ret = pthread_setaffinity_np(pid, sizeof(cpu_set_t), mask); /* 设置cpu 亲和性(affinity)*/
    if (ret < 0)
    {
        printf("%s:%d:", __FUNCTION__, __LINE__);
        perror("faild sched_setaffinity");
        return -1;
    }
    //printf("bind_cpu_cores success\n");
    return 0;
}
int bind_fork_cpu_cores(cpu_set_t *mask)
{

    int ret = sched_setaffinity(0, sizeof(cpu_set_t), mask);
    if (ret < 0)
    {
        printf("%s:%d:", __FUNCTION__, __LINE__);
        perror("faild sched_setaffinity");
        return -1;
    }
    //printf("bind_cpu_cores success\n");
    return 0;
}
void cpu_get(char* thread_name)
{
     usleep(10000);
    {
        int ret;
        cpu_set_t get_cpus;
        CPU_ZERO(&get_cpus);
        ret = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &get_cpus);
        if (ret < 0)
        {
            perror("faild sched_getaffinity");
        }
        printf("%s [%ld] is running in processor:",thread_name, pthread_self());
        for (int i = 0; i < 4; i++)
        {
            if (CPU_ISSET(i, &get_cpus))
            {
                printf("%d ", i);
            }
        }
        printf("\n");
    }
}
int create_pthread(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine)(void *), void *arg, int* cpus_arr,int nums)
{
    int ret;
    cpu_set_t mask;
    ret = set_cpus_mask(cpus_arr, nums, &mask);
    if (ret < 0)
    {
        printf("set_cpus_mask failed\n");
        return -1;
    }
    ret = pthread_create(thread, NULL, start_routine, arg);
    if (ret < 0)
    {
        printf("pthread_create failed\n");
        return -1;
    }
    ret = bind_pthread_cpu_cores(&mask, *thread);
    if (ret < 0)
    {
        printf("bind_pthread_cpu_cores failed\n");
        return -1;
    }
    
    usleep(100000);
}

int pthread_attribute_init(pthread_attr_t *attr){
    return pthread_attr_init(attr);
}
int pthread_attribute_destory(pthread_attr_t *attr){
    return pthread_attr_destroy(&attr);
}
int pthread_set_inheritsched(pthread_attr_t *attr,int __inherit){
    return pthread_attr_setinheritsched(attr, __inherit);
}
int pthread_set_schedpolicy(pthread_attr_t *attr,int policy){
    pthread_attr_setschedpolicy(attr, policy);
}

cpus_set.h


#ifndef __CPUS_SET_H__
#define __CPUS_SET_H__

#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sched.h>
#include <stdlib.h>

/*
    return : Number of CPU cores
*/
extern int get_cpu_num();
/*
    
*/
extern int set_cpus_mask(int *cpus_arr, int nums,cpu_set_t* mask);

extern int del_cpu_mask(int cpu_num,cpu_set_t* mask);

extern int bind_cpu_cores(cpu_set_t* mask,pthread_t pid);

extern int create_pthread(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine)(void *), void *arg, int *cpus_arr,int nunms);

#endif

main

#define _GNU_SOURCE

#include "cpus_set.h"
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sched.h>
#include <stdlib.h>
void printf_str(char *str)
{
    printf("%s", str);
}
void *thread_run1()
{
    usleep(10000);
    {
        int ret;
        cpu_set_t get_cpus;
        CPU_ZERO(&get_cpus);
        ret = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &get_cpus);
        if (ret < 0)
        {
            perror("faild sched_getaffinity");
        }
        printf("pthread_run1[%ld] is running in processor:", pthread_self());
        for (int i = 0; i < 4; i++)
        {
            if (CPU_ISSET(i, &get_cpus))
            {
                printf("%d ", i);
            }
        }
        printf("\n");
    }
    int policy;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct sched_param param;
    pthread_getschedparam(pthread_self(), &policy, &param);
    while (1)
    {
        //usleep(10000);
        //printf("pthtrad_run1 on cpu[%d] policy = %d ,param.__sched_priority = %d!\n", sched_getcpu(),policy,param.__sched_priority );
        printf_str("thread_run1 is running!\n");
    }
    pthread_exit(NULL);
}
void *thread_run2()
{
    usleep(10000);
    {
        int ret;
        cpu_set_t get_cpus;
        CPU_ZERO(&get_cpus);
        ret = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &get_cpus);
        if (ret < 0)
        {
            perror("faild sched_getaffinity");
        }
        printf("pthread_run2[%ld] is running in processor:", pthread_self());
        for (int i = 0; i < 4; i++)
        {
            if (CPU_ISSET(i, &get_cpus))
            {
                printf("%d ", i);
            }
        }
        printf("\n");
    }
    int policy;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct sched_param param;
    pthread_getschedparam(pthread_self(), &policy, &param);
    while (1)
    {
        //usleep(10000);
        //printf("pthtrad_run2 on cpu[%d] policy = %d ,param.__sched_priority = %d!\n", sched_getcpu(),policy,param.__sched_priority );
        printf_str("thread_run2 is running!\n");
    }
    pthread_exit(NULL);
}
void *thread_run3()
{
   
    int policy;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct sched_param param;
    pthread_getschedparam(pthread_self(), &policy, &param);
    while (1)
    {
        //usleep(10000);
        //printf("pthtrad_run3 on cpu[%d] policy = %d ,param.__sched_priority = %d!\n", sched_getcpu(),policy,param.__sched_priority );
        printf_str("thread_run3 is running!\n");
    }
    pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
    pthread_t th1, th2, th3;

    pthread_attr_t attr;
    struct sched_param sched;
    int ret;
    int cpu_arr1[1] = {0};
    cpu_set_t mask1;
    sched.__sched_priority = 99;
    pthread_attr_init(&attr);
    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); //要使优先级其作用必须要有这句话
    pthread_attr_setschedpolicy(&attr, SCHED_RR);                //改变线程调度策略
    pthread_attr_setschedparam(&attr, &sched);                   //设置线程优先级
    ret = create_pthread(&th1, &attr, thread_run1, NULL, cpu_arr1,sizeof(cpu_arr1)/sizeof(cpu_arr1[0]));
    if (ret < 0)
    {
        printf("%s:%d:create_pthread1 fail\n", __FUNCTION__, __LINE__);
    }
    pthread_attr_destroy(&attr);

    int cpu_arr2[1] = {0};
    cpu_set_t mask2;
    sched.__sched_priority = 50;
    pthread_attr_init(&attr);
    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); //要使优先级其作用必须要有这句话
    pthread_attr_setschedpolicy(&attr, SCHED_RR);                //改变线程调度策略
    pthread_attr_setschedparam(&attr, &sched);                   //设置线程优先级
    ret = create_pthread(&th2, &attr, thread_run2, NULL, cpu_arr2,sizeof(cpu_arr2)/sizeof(cpu_arr2[0]));
    if (ret < 0)
    {
        printf("%s:%d:create_pthread2 fail\n", __FUNCTION__, __LINE__);
    }
    pthread_attr_destroy(&attr);

    int cpu_arr3[1] = {0};
    cpu_set_t mask3;
    sched.__sched_priority = 1;
    pthread_attr_init(&attr);
    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); //要使优先级其作用必须要有这句话
    pthread_attr_setschedpolicy(&attr, SCHED_RR);                //改变线程调度策略
    pthread_attr_setschedparam(&attr, &sched);                   //设置线程优先级
    ret = create_pthread(&th3, &attr, thread_run3, NULL, cpu_arr3,sizeof(cpu_arr3)/sizeof(cpu_arr3[0]));
    if (ret < 0)
    {
        printf("%s:%d:create_pthread3 fail\n", __FUNCTION__, __LINE__);
    }
    pthread_attr_destroy(&attr);

    pthread_join(th1, NULL);
    pthread_join(th2, NULL);
    pthread_join(th3, NULL);

    return 0;
}
#if 0
#define _GNU_SOURCE

#include "cpus_set.h"
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sched.h>
#include <stdlib.h>
void printf_str(char *str)
{
    printf("%s", str);
}
void *thread_run1()
{
    usleep(10000);
    {
        int ret;
        cpu_set_t get_cpus;
        CPU_ZERO(&get_cpus);
        ret = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &get_cpus);
        if (ret < 0)
        {
            perror("faild sched_getaffinity");
        }
        printf("pthread_run1[%ld] is running in processor:", pthread_self());
        for (int i = 0; i < 4; i++)
        {
            if (CPU_ISSET(i, &get_cpus))
            {
                printf("%d ", i);
            }
        }
        printf("\n");
    }
    int policy;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct sched_param param;
    pthread_getschedparam(pthread_self(), &policy, &param);
    while (1)
    {
        //usleep(10000);
        //printf("pthtrad_run1 on cpu[%d] policy = %d ,param.__sched_priority = %d!\n", sched_getcpu(),policy,param.__sched_priority );
        printf_str("thread_run1 is running!\n");
    }
    pthread_exit(NULL);
}
void *thread_run2()
{
    usleep(10000);
    {
        int ret;
        cpu_set_t get_cpus;
        CPU_ZERO(&get_cpus);
        ret = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &get_cpus);
        if (ret < 0)
        {
            perror("faild sched_getaffinity");
        }
        printf("pthread_run2[%ld] is running in processor:", pthread_self());
        for (int i = 0; i < 4; i++)
        {
            if (CPU_ISSET(i, &get_cpus))
            {
                printf("%d ", i);
            }
        }
        printf("\n");
    }
    int policy;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct sched_param param;
    pthread_getschedparam(pthread_self(), &policy, &param);
    while (1)
    {
        //usleep(10000);
        //printf("pthtrad_run2 on cpu[%d] policy = %d ,param.__sched_priority = %d!\n", sched_getcpu(),policy,param.__sched_priority );
        printf_str("thread_run2 is running!\n");
    }
    pthread_exit(NULL);
}
void *thread_run3()
{
   
    int policy;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    struct sched_param param;
    pthread_getschedparam(pthread_self(), &policy, &param);
    while (1)
    {
        //usleep(10000);
        //printf("pthtrad_run3 on cpu[%d] policy = %d ,param.__sched_priority = %d!\n", sched_getcpu(),policy,param.__sched_priority );
        printf_str("thread_run3 is running!\n");
    }
    pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
    pthread_t th1, th2, th3;

    pthread_attr_t attr;
    struct sched_param sched;
    int ret;
    int cpu_arr1[1] = {0};
    cpu_set_t mask1;
    sched.__sched_priority = 99;
    pthread_attr_init(&attr);
    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); //要使优先级其作用必须要有这句话
    pthread_attr_setschedpolicy(&attr, SCHED_RR);                //改变线程调度策略
    pthread_attr_setschedparam(&attr, &sched);                   //设置线程优先级
    ret = create_pthread(&th1, &attr, thread_run1, NULL, cpu_arr1,sizeof(cpu_arr1)/sizeof(cpu_arr1[0]));
    if (ret < 0)
    {
        printf("%s:%d:create_pthread1 fail\n", __FUNCTION__, __LINE__);
    }
    pthread_attr_destroy(&attr);

    int cpu_arr2[1] = {0};
    cpu_set_t mask2;
    sched.__sched_priority = 50;
    pthread_attr_init(&attr);
    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); //要使优先级其作用必须要有这句话
    pthread_attr_setschedpolicy(&attr, SCHED_RR);                //改变线程调度策略
    pthread_attr_setschedparam(&attr, &sched);                   //设置线程优先级
    ret = create_pthread(&th2, &attr, thread_run2, NULL, cpu_arr2,sizeof(cpu_arr2)/sizeof(cpu_arr2[0]));
    if (ret < 0)
    {
        printf("%s:%d:create_pthread2 fail\n", __FUNCTION__, __LINE__);
    }
    pthread_attr_destroy(&attr);

    int cpu_arr3[1] = {0};
    cpu_set_t mask3;
    sched.__sched_priority = 1;
    pthread_attr_init(&attr);
    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); //要使优先级其作用必须要有这句话
    pthread_attr_setschedpolicy(&attr, SCHED_RR);                //改变线程调度策略
    pthread_attr_setschedparam(&attr, &sched);                   //设置线程优先级
    ret = create_pthread(&th3, &attr, thread_run3, NULL, cpu_arr3,sizeof(cpu_arr3)/sizeof(cpu_arr3[0]));
    if (ret < 0)
    {
        printf("%s:%d:create_pthread3 fail\n", __FUNCTION__, __LINE__);
    }
    pthread_attr_destroy(&attr);

    pthread_join(th1, NULL);
    pthread_join(th2, NULL);
    pthread_join(th3, NULL);

    return 0;
}

#endif 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

linux线程设置cpu亲和性与调度方式及优先级 的相关文章

  • 计算机网络体系结构

    一 计算机网络概述 计算机网络的概念 组成与功能 概念 功能 组成 工作方式 分类 计算机网络的标准化工作及相关组织 标准分类 计算机网络的标准化工作 相关组织 二 计算机网络体系结构与参考模型 计算机网络分层结构 计算机网络体系结构 为什
  • KL25嵌入式实验考核

    KL25嵌入式实验考核 xff08 6 43 xff09 404 页面找不到 说明资源在审核中 1 利用 KL25 小板实现 控制红色 LED 灯每隔 2 秒钟亮暗变换的同时 在 PC 机上显示 MCU 的计时时间 xff0c MCU 的初
  • 自制PMW3901光流模块

    PMW3901光流Sensor体积小 功耗低 精度高 xff0c 效果非常好 xff0c 自己做了一个光流小模块带TOF测距 xff0c 使用Pixracer 43 PX4固件 xff0c 测试效果还不错 测试视频 xff1a https
  • 模数转换ADC模块

    通用基础知识 ADC模块是嵌入式应用中重要的组成部分 xff0c 是嵌入式系统与外界连接的纽带 xff0c 是在测控系统中的重要内容 ADC模块 xff1a 即模数转换模块 AD转换模块 xff0c 功能是将电压信号转换为相应的数字信号 实
  • 实验五 Flash在线编程实验

    一 xff0e 实验目的 xff08 1 xff09 掌握 Flash 存储器在线编程的基本概念 xff08 2 xff09 熟悉 Flash 存储器的在线编程擦除和写入的步骤 xff08 3 xff09 进一步深入理解 MCU 和 C 串
  • Install OpenCV+ Python in Ubuntu

    1 VMware安装ubuntu 不建议在Windows下学习 安装教程 Tip1 xff1a Ubuntu安装结束后无法正常联网 然后就是等待漫长的更新 Tip2 文件含有中文名 打开终端 export LANG 61 en US xdg
  • Tracking motion in video

    Tracking motion in video Download the source code to Ball Tracking with OpenCV
  • parse command line arguments

    parse command line arguments
  • 计算机网络

    计算机网络 一 计算机网络体系结构 二 物理层 三 数据链路层 四 网络层 五 运输层 六 应用层
  • 【c++初学】遇到问题:对xxx未定义的引用

    在编译的时候遇到了 未定义引用 root 64 czp span class token operator span PC span class token operator span span class token operator s
  • 在同一个浏览器上打开同一个网址只打开一个窗口的方法

    具体问题看图吧 xff0c 我自己也说不清楚 具体操作如下 xff1a target属性的功能之一是可以在同一个浏览器中只打开被标记相同的网页窗口 利用这一功能可以实现以上问题 target属性链接地址 xff1a http www w3s
  • esp32 Arduino IDE读取航模接收机SBUS信号

    库函数下载链接https download csdn net download qq 40925542 87207281 该库函数适用于具有多个串口的开发板 xff0c esp32中测试通过 xff0c 测试代码如下 xff1a inclu
  • curl 401 unauthorized解决

    用curl获取web信息时遇到了401unauthorized错误 用下面的命令解决了 xff1a span class token function curl span insecure anyauth u admin password
  • git自建服务器-借助蒲公英实现远程访问

    git自建服务器 借助蒲公英实现远程访问 本文涉及蒲公英组网 xff0c 这里大家可以参考蒲公英官网组网教程 使用的硬件 蒲公英x3a 路由器 xff1a 用于智能组网 xff0c 实现内网穿透vpn功能 xff1b orange pi3
  • sockaddr与sockaddr_in结构体简介

    span class token keyword struct span sockaddr span class token punctuation span span class token keyword unsigned span s
  • ROS入门(二)——创建功能包和工作空间

    提示 xff1a 文章写完后 xff0c 目录可以自动生成 xff0c 如何生成可参考右边的帮助文档 文章目录 前言一 工作空间 xff08 workspace xff09 xff1f 二 创建工作空间 xff08 workspace xf
  • SpringBoot异常处理-SimpleMappingExceptionResolver(四)

    异常处理 SimpleMappingExceptionResolver 配置 SimpleMappingExceptionResolver 处理异常 在全局异常类中添加一个方法完成异常的同一处理 结果是只不返回参数 没有上一个博客方法好 但
  • Matplotlib三维绘图,这一篇就够了

    Matplotlib三维绘图 xff0c 这一篇就够了 1 效果图1 1 3D线效果图1 2 3D散点效果图1 3 3D随机颜色散点效果图1 4 3D散点不同mark点效果图1 5 3D线框效果图1 6 3D曲面不透明效果图1 7 3D曲面
  • C++编程永不过时的语言,原因何在?

    想要知道C 43 43 到底如何你首先要了解C 43 43 的特性 C 43 43 既保留了C语言的有效性 灵活性 便于移植等全部精华和特点 xff0c 又添加了面向对象编程的支持 xff0c 具有强大的编程功能 xff0c 可方便地构造出
  • px4ctrl代码解读-px4ctrl_node

    头文件 include lt ros ros h gt include 34 PX4CtrlFSM h 34 include lt signal h gt 1 初始化节点 ros init argc argv 34 px4ctrl 34 r

随机推荐