Linux c++ 指定程序再四核中的某一核上运行

46 篇文章 0 订阅

获取到多核程序:

/*
 * =====================================================================================
 *
 *       Filename:  get_cpu_core_num.c
 *
 *    Description:  获取CPU可用核数并绑定某核运行
 *
 *        Version:  1.0
 *        Created:  2013年08月09日 13时01分23秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Hurley (LiuHuan), liuhuan1992@gmail.com
 *        Company:  Class 1107 of Computer Science and Technology
 * https://github.com/hurley25/linux_system_call/blob/master/src/get_cpu_core_num.c
 *
 * =====================================================================================
 */

#define _GNU_SOURCE 

#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <sys/sysinfo.h>

int main(int argc, char *argv[])
{
	int cpu_core_num = get_nprocs();

	printf("CPU has %d core\n", cpu_core_num);
	
	cpu_set_t mask;
	cpu_set_t get;

	int myid, i;
	for (myid = 0; myid < cpu_core_num; myid++) {
		CPU_ZERO(&mask);
		CPU_SET(myid, &mask);
		if (sched_setaffinity(0, sizeof(mask), &mask) == -1) {
			printf("warning: could not set CPU affinity, continuing\n");
		}

		CPU_ZERO(&get);
		if (sched_getaffinity(0, sizeof(get), &get) == -1) {
			printf("warning: cound not get cpu affinity\n");
		}
		for (i = 0; i < cpu_core_num; i++) {
			if (CPU_ISSET(i, &get)) {
				printf("this process %d is running processor : %d\n",getpid(), i);
			}
		}
	}

	return EXIT_SUCCESS;
}

再单核上运行:

#define _GNU_SOURCE 

#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <sys/sysinfo.h>

void start()
{
    while (1)
    {
        printf("hello world %d\n", random());

        sleep(1);
    }
}

int main(int argc, char *argv[])
{
	int cpu_core_num = get_nprocs();

	printf("CPU has %d core\n", cpu_core_num);
	
	cpu_set_t mask;
	cpu_set_t get;

	int myid = 1, i = 1;

    CPU_ZERO(&mask);
	CPU_SET(myid, &mask);
	if (sched_setaffinity(0, sizeof(mask), &mask) == -1) {
		printf("warning: could not set CPU affinity, continuing\n");
	}

	CPU_ZERO(&get);
	if (sched_getaffinity(0, sizeof(get), &get) == -1) {
		printf("warning: cound not get cpu affinity\n");
	}
			
    if (CPU_ISSET(i, &get)) {
		printf("this process %d is running processor : %d\n",getpid(), i);
        start();
	}
		

	return EXIT_SUCCESS;
}

第一个核为0,第二个核为1,运行时看pid

$ taskset -p pid
 pid 1567's current affinity mask: 4
说明  4由十进制转二进制(0010),判断再2核上运行

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值