简体   繁体   English

创建线程之前的Pthread亲和性

[英]Pthread affinity before create threads

I need to set the affinity (thread to core, eg: 1st thread to 1st core) before creating a thread. 我需要在创建线程之前设置亲缘关系(线程到核心,例如:第一个线程到第一个核心)。 Something like KMP_AFFINITY in OpenMP . OpenMP KMP_AFFINITY Is it possible? 可能吗?

edit: I try in this way, but dont' work :/ 编辑:我试试这种方式,但不要工作:/

void* DoWork(void* args)
{
    int nr = (int)args;
    printf("Wątek: %d, ID: %d, CPU: %d\n", nr,pthread_self(), sched_getcpu());  
}


int main()
{   
    int count = 8;
    pthread_t threads[count];

    pthread_attr_t attr;
    cpu_set_t mask;
    CPU_ZERO(&mask);
    pthread_attr_init(&attr);

    for (int i = 0; i < count ; i++)
         CPU_SET(i, &mask);

    pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &mask);

    for(int i=0; i<count ; i++)
    {

        pthread_create(&threads[i], &attr, DoWork, (void*)i);
    }

    for(int i=0; i<count ; i++)
    {
        pthread_join(threads[i], NULL);
    }
}

As mentioned before you should use pthread_attr_setaffinity_np to bind a thread to a specific core. 如前所述,您应该使用pthread_attr_setaffinity_np将线程绑定到特定核心。 The number of CPU cores available in your system can be retrieved (see code below). 可以检索系统中可用的CPU核心数(请参阅下面的代码)。

While creating the threads with pthread_create , each time you have to pass an instance of pthread_attr_t which is set with appropriate cpu_set_t . 在使用pthread_create创建线程时,每次必须传递使用适当的cpu_set_t设置的pthread_attr_t实例。 Every time you have to either clear the cpu_set_t or remove the previously entered number (I chose the former option) before adding the next identifier of CPU core to the set. 每次你必须清除cpu_set_t或删除先前输入的数字(我选择前一个选项),然后再将下一个CPU核心标识符添加到集合中。 You need to have exactly one CPU in the set when creating the thread if you want to determine exactly on which CPU the thread will be executed (see code below). 如果要确定线程将在哪个CPU上执行,请在创建线程时在集合中只需要一个CPU(参见下面的代码)。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void* DoWork(void* args) {
    printf("ID: %lu, CPU: %d\n", pthread_self(), sched_getcpu());
    return 0;
}

int main() {   

    int numberOfProcessors = sysconf(_SC_NPROCESSORS_ONLN);
    printf("Number of processors: %d\n", numberOfProcessors);

    pthread_t threads[numberOfProcessors];

    pthread_attr_t attr;
    cpu_set_t cpus;
    pthread_attr_init(&attr);

    for (int i = 0; i < numberOfProcessors; i++) {
       CPU_ZERO(&cpus);
       CPU_SET(i, &cpus);
       pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
       pthread_create(&threads[i], &attr, DoWork, NULL);
    }

    for (int i = 0; i < numberOfProcessors; i++) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}

您可以调用pthread_self()来获取主线程的线程ID,并在pthread_setaffinity_np中使用它。

您可以使用pthread_attr_setaffinity_nppthread_create函数设置关联属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM