在创建线程之前,我需要设置亲和力(线程到核心,例如:第一个线程到第一个核心)。就像是KMP_AFFINITY
in OpenMP
。是否可以?
编辑:
我以这种方式尝试,但不起作用:/
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);
}
}
正如之前提到的,你应该使用pthread_attr_setaffinity_np
将线程绑定到特定的核心。可以检索系统中可用的 CPU 核心数量(请参阅下面的代码)。
创建线程时pthread_create
,每次你必须传递一个实例pthread_attr_t
这是设置适当的cpu_set_t
。每次你必须清除cpu_set_t
或者在将下一个 CPU 核心标识符添加到集合之前删除之前输入的数字(我选择了前一个选项)。如果您想准确确定线程将在哪个 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)