技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> Linux --> Linux下进程绑定多CPU运行

Linux下进程绑定多CPU运行

浏览:5601次  出处信息

在服务器上,我们经常会有多个CPU的情况,而此时如果把进程都绑定在一个CPU上,那么对资源太多浪费了,下面的代码就实现了如何将程序绑定在不同的cpu上。传入参数代表绑定第几个cpu(从0开始计算)

//cpu_test.cpp
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/sysinfo.h>
#include<unistd.h>
//#define __USE_GNU
#include<sched.h>
#include<ctype.h>
#include<string.h>
int main(int argc, char* argv[])
{
        int num = sysconf(_SC_NPROCESSORS_CONF);
        int created_thread = 0;
        int myid;
        int i;
        int j = 0;
        cpu_set_t mask;
        cpu_set_t get;
        if (argc != 2)
        {
                printf(“usage : ./cpu num\n”);
                exit(1);
        }
        myid = atoi(argv[1]);
        printf(“system has %i processor(s). \n”, num);
        CPU_ZERO(&mask);
        CPU_SET(myid, &mask);
        if (sched_setaffinity(0, sizeof(mask), &mask) == -1)
        {
                printf(“warning: could not set CPU affinity, continuing…\n”);
        }
        while (1)
        {
    usleep(10000);
                CPU_ZERO(&get);
                if (sched_getaffinity(0, sizeof(get), &get) == -1)
                {
                        printf(“warning: cound not get cpu affinity, continuing…\n”);
                }
                for (i = 0; i < num; i++)
                {
                        if (CPU_ISSET(i, &get))
                        {
                                printf(“this process %d is running processor : %d\n”,getpid(), i);
                        }
                }
        }
        return 0;
}
//g++ cpu_test.cpp -o cpu_test

下载源代码

下面解释一下,里面用到的函数:
首先解释一下一个叫CPU亲和力

建议继续学习:

  1. Linux如何统计进程的CPU利用率    (阅读:14098)
  2. Linux内存点滴 用户进程内存空间    (阅读:11038)
  3. 解剖CPU    (阅读:7925)
  4. Oracle MTS模式下 进程地址与会话信息    (阅读:6882)
  5. 深入理解Nginx之调试优化技巧    (阅读:6482)
  6. 查看 CPU, Memory, I/O and NetFlow    (阅读:6239)
  7. Linux上进程的表示以及入门    (阅读:6084)
  8. 如何查看Linux 硬件配置信息    (阅读:5700)
  9. 从Java视角理解CPU上下文切换(Context Switch)    (阅读:5349)
  10. 分析进程内存分配情况,解决程序性能问题    (阅读:5122)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
  • 作者:Dante    来源: Vimer
  • 标签: CPU 进程
  • 发布时间:2009-12-18 09:33:13
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1