Linux下进程绑定多CPU运行

Vimer 2009-12-18 09:33:13 累计浏览 7,556 次

在服务器上,我们经常会有多个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. NGINX Gateway Fabric 2.8: IP allow and deny lists, passive health checks, and cookie-based session persistence (2026-11-14 01:10:02)
  2. NGINX Ingress Controller 5.7: HTTP/2 to your upstreams, Opaque Secrets, and cert-manager challenges behind HTTPS redirects (2026-11-14 00:10:02)
  3. Hexo 文章一键发布到微信公众号 (2026-11-13 19:10:02)

查看更多 DevOps 文章 →

建议继续学习

  1. Linux如何统计进程的CPU利用率 (累计阅读 16,953)
  2. 我的 RHCA 之路 (累计阅读 14,368)
  3. Linux内存点滴 用户进程内存空间 (累计阅读 13,956)
  4. 给程序员新手的一些建议 (累计阅读 13,518)
  5. Linux 性能监控、测试、优化工具 (累计阅读 13,460)
  6. 关于linux内存free的一些事情 (累计阅读 13,399)
  7. Google怎么用linux (累计阅读 13,158)
  8. ps - 按进程消耗内存多少排序 (累计阅读 12,983)
  9. Linux Used内存到底哪里去了? (累计阅读 12,523)
  10. find命令的一点注意事项 (累计阅读 12,370)