为线程绑定核

在一些嵌入式设备上,把某些特定的线程绑定在特定的核上,减少核间切换,有可能获得更高的性能

#define _GNU_SOURCE //necessary
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sched.h>

void* myfun(void *arg)
{
    cpu_set_t mask;
    cpu_set_t get;
    char buf[256];
    int i;
    int j;
    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 to core %d failed\n", i);
        }
        CPU_ZERO(&get);
        // 使用getaffinity可以知道当前thread在哪个核上
        if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0) {
            fprintf(stderr, "get thread affinity failed\n");
        }
        for (j = 0; j < num; j++) {
            // 使用CPU_ISSET 来测试上面getaffinity的到底是哪个核
            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, myfun, NULL) != 0) {
        fprintf(stderr, "thread create failed\n");
        return -1;
    }
    pthread_join(tid, NULL);
    return 0;
}

 

posted on 2021-12-04 17:42  疾速瓜牛  阅读(218)  评论(0编辑  收藏  举报

导航