Linux如何将两个线程绑定,linux下将不同线程绑定到不同core和cpu上——pthread_setaffinity_np...

int cpu = sched_getcpu();

printf("### running on cpu: %d

", cpu);

int cpu_num = sysconf(_SC_NPROCESSORS_CONF);

printf("### cpu num: %d

", cpu_num);

if (cpu_id >= cpu_num)

{

printf("### assign cpu id should not >= %d

", cpu_num);

return -1;

}

if (cpu_id >= 0)

int code = assign_cpu(cpu_id, cpu_num);

int assign_cpu(int cpu, int cpus)

{

cpu_set_t mask;

cpu_set_t get;

CPU_ZERO(&mask);

CPU_SET(cpu, &mask);

if (sched_setaffinity(getpid(), sizeof(mask), &mask) == -1) {

printf("Set CPU affinity failue, ERROR:%s

", strerror(errno));

return -1;

}

timespec wait_time = {0, 1000000000};

nanosleep(&wait_time, 0);

CPU_ZERO(&get);

if (sched_getaffinity(getpid(), sizeof(get), &get) == -1)

{

printf("get CPU affinity failue, ERROR:%s

", strerror(errno));

return -1;

}

for(int i = 0; i < cpus; i++)

{

if (CPU_ISSET(i, &get))

{

printf("this process %d of running processor: %d

", getpid(), i);

}

}

return 0;

}

# define __CPU_SETSIZE 1024

# define __NCPUBITS (8 * sizeof (__cpu_mask))

typedef unsigned long int __cpu_mask;

# define __CPUELT(cpu) ((cpu) / __NCPUBITS)

# define __CPUMASK(cpu) ((__cpu_mask) 1 << ((cpu) % __NCPUBITS))

typedef struct

{

__cpu_mask __bits[__CPU_SETSIZE / __NCPUBITS];

} cpu_set_t;

# define __CPU_ZERO(cpusetp)

do {

unsigned int __i;

cpu_set_t *__arr = (cpusetp);

for (__i = 0; __i < sizeof (cpu_set_t) / sizeof (__cpu_mask); ++__i)

__arr->__bits[__i] = 0;

} while (0)

# define __CPU_SET(cpu, cpusetp)

((cpusetp)->__bits[__CPUELT (cpu)] |= __CPUMASK (cpu))

# define __CPU_CLR(cpu, cpusetp)

((cpusetp)->__bits[__CPUELT (cpu)] &= ~__CPUMASK (cpu))

# define __CPU_ISSET(cpu, cpusetp)

(((cpusetp)->__bits[__CPUELT (cpu)] & __CPUMASK (cpu)) != 0)

注意的地方:如果用CPU_SET这个宏来设置那么可以直接用0,1,2作为cpu的id。

如果直接对mask赋值,需要注意是按照bit来的:

30     unsigned long mask = 1; /* processor 0 */

31

32     /* bind process to processor 0 */

33     if (sched_setaffinity(0, sizeof(mask), &mask) <0) {

34         perror("sched_setaffinity");

35     }

36

37     /* waste some time so the work is visible with "top" */

38     printf ("result: %f

", waste_time (2000));

39

40     mask = 2; /* process switches to processor 1 now */

41     if (sched_setaffinity(0, sizeof(mask), &mask) <0) {

42         perror("sched_setaffinity");

43     }

44

45     /* waste some more time to see the processor switch */

46     printf ("result: %f

", waste_time (2000));

47 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值