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

    int cpu = sched_getcpu();
    printf("### running on cpu: %d\n", cpu);

    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);


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\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;
}


  

# 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\n", 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\n", waste_time (2000));
47 }

 

posted @ 2019-09-10 10:41  小 楼 一 夜 听 春 雨  阅读(...)  评论(... 编辑 收藏