linux 线程 cpu分配,LINUX中物理CPU资源的分配是基于线程还是进程

大概的介绍一下Linux 的指定CPU运行,包括进程和线程。linux下的top命令是可以查看当前的cpu的运行状态,按1可以查看系统有多少个CPU,以及每个CPU的运行状态。

可是如何查看线程的CPU呢?top

-Hp pid,pid就是你当前程序的进程号,如果是多线程的话,是可以查看进程内所有线程的CPU和内存使用情况。

pstree可以查看主次线程,同样的pstree -p pid。可以查看进程的线程情况。

taskset这个其实才是重点,可以查看以及设置当前进程或线程运行的CPU(设置亲和力)。

taskset -pc pid,查看当前进程的cpu,当然有的时候不只是一个,taskset -pc cpu_num pid ,cpu_num就是设置的cpu。

这样的话基本的命令和操作其实大家都知道了,接下来就是在代码中完成这些操作,并通过命令去验证代码的成功率。

进程制定CPU运行:

[cpp] view plain copy

#include

#include

#include

#include

#include

#define __USE_GNU

#include

#include

#include

int main(int argc, char* argv[])

{

//sysconf获取有几个CPU

int num = sysconf(_SC_NPROCESSORS_CONF);

int created_thread = 0;

int myid;

int i;

int j = 0;

//原理其实很简单,就是通过cpu_set_t进行位与操作

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)

{

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;

}

进程设置CPU运行,其实只能是单线程。多线程设定CPU如下:

[cpp] view plain copy

#define _GNU_SOURCE

#include

#include

#include

#include

#include

#include

void *myfun(void *arg)

{

cpu_set_t mask;

cpu_set_t get;

char buf[256];

int i;

int j;

//同样的先去获取CPU的个数

int num = sysconf(_SC_NPROCESSORS_CONF);

printf("system has %d processor(s)\n", num);

for (i = 0; i < num; i++) {

CPU_ZERO(&mask);

CPU_SET(i, &mask);

//这个其实和设置进程的亲和力基本是一样的

if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {

fprintf(stderr, "set thread affinity failed\n");

}

CPU_ZERO(&get);

if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0) {

fprintf(stderr, "get thread affinity failed\n");

}

for (j = 0; j < num; j++)

{

if (CPU_ISSET(j, &get))

{

printf("thread %d is running in processor %d\n", (int)pthread_self(), j);

}

}

j = 0;

while (j++ < 100000000) {

memset(buf, 0, sizeof(buf));

}

}

pthread_exit(NULL);

}

int main(int argc, char *argv[])

{

pthread_t tid;

if (pthread_create(&tid, NULL, (void *)myfun, NULL) != 0)

{

fprintf(stderr, "thread create failed\n");

return -1;

}

pthread_join(tid, NULL);

return 0;

}

取消

评论

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值