创建线程之前的Pthread关联 [英] Pthread affinity before create threads

查看:86
本文介绍了创建线程之前的Pthread关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建线程之前,我需要设置亲和力(线程到核心,例如:1st线程到1st core)。类似于 OpenMP 中的 KMP_AFFINITY

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. 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前面提到的应该使用 pthread_attr_setaffinity_np 将线程绑定到特定的内核。可以检索系统中可用的CPU内核数(请参见下面的代码)。

As mentioned before you should use pthread_attr_setaffinity_np to bind a thread to a specific core. The number of CPU cores available in your system can be retrieved (see code below).

每次使用 pthread_create 创建线程时,每次必须传递的实例时pthread_attr_t 设置为适当的 cpu_set_t 。每次您必须清除 cpu_set_t 或删除先前输入的数字(我选择前一个选项),然后再将下一个CPU内核标识符添加到集合中时,才可以。如果要确定线程将在哪个CPU上执行,则在创建线程时必须在集合中只有一个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. 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. 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).

#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关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆