linux下将不同线程绑定到不同core和cpu上-pthread_setaffinity_np

【自取】最近整理的,有需要可以领取学习:

cpp;gutter:true; int cpu = sched_getcpu(); printf("### running on cpu: %d\n", cpu);</p> <pre><code>int cpu_num = sysconf(_SC_NPROCESSORS_CONF); printf("### cpu num: %d\n", cpu_num); if (cpu_id >= cpu_num) { printf("### assign cpu id should not >= %d\n", cpu_num); return -1; } if (cpu_id >= 0) int code = assign_cpu(cpu_id, cpu_num); </code></pre> <p>int assign_cpu(int cpu, int cpus) { cpu_set_t mask; cpu_set_t get; CPU_ZERO(&mask); CPU_SET(cpu, &mask);</p> <pre><code>if (sched_setaffinity(getpid(), sizeof(mask), &mask) == -1) { printf("Set CPU affinity failue, ERROR:%s\n", 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\n", strerror(errno)); return -1; } for(int i = 0; i < cpus; i++) { if (CPU_ISSET(i, &get)) { printf("this process %d of running processor: %d\n", getpid(), i); } } return 0; </code></pre> <p>}</p> <pre><code> ;gutter:true;
# 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。

如果您直接为掩码赋值,需要注意的是,它是基于位的:

[En]

If you assign a value to mask directly, it should be noted that it is based on bit:

30     unsigned long mask = 1; /* processor 0 */
31  
32     /* bind process to processor 0 */
33     if (sched_setaffinity(0, sizeof(mask), &mask)

Original: https://www.cnblogs.com/kex1n/p/11496078.html
Author: 小 楼 一 夜 听 春 雨
Title: linux下将不同线程绑定到不同core和cpu上-pthread_setaffinity_np

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/7101/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

发表回复

登录后才能评论
免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部