Linux下进程绑定多CPU运行
2015-07-24 09:28
246 查看
在服务器上,我们经常会有多个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
出处:http://blogread.cn/it/article/837?f=sa
//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
出处:http://blogread.cn/it/article/837?f=sa
相关文章推荐
- Linux命令-安全复制命令:scp
- 嵌入式linux之输入子系统
- 获取linux系统的cup信息,内存信息c代码
- 几种查看linux版本信息的方法
- linux下查看cpu信息
- linux 加载ISO
- linux 查询Mysql的安装位置
- centos6.5下postgresql9.4.3安装与配置
- CentOS中JIRA6.3.6安装配置过程
- [Linux & SVN] SVN介绍及Linux下SVN命令收录
- Linux中断处理与定时器
- 在Linux上安装ipmitool
- Centos6.5添加Epel和Remi源安装Lamp环境
- 【学习笔记】Linux的命令总结(三)
- linux中mmap文件到内存中,该进程发生错误被挂掉后mmap映射的内存能否写回到文件中的问题
- linux 关于session缓存丢失,自己掉坑里面了
- CentOS-7磁盘扩容之殇
- [Linux C]自己写的串口缓冲区
- [嵌入式Linux驱动]S5PV210的烟雾传感器Linux驱动
- Linux mkdir、tar 和 kill 命令的 4 个有用小技巧