pthread_attr_setaffinity_np不会返回或抛出错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pthread_attr_setaffinity_np不会返回或抛出错误相关的知识,希望对你有一定的参考价值。
我正在尝试启动几个线程,每个线程都有自己的核心(4个核心 - > 4个线程,例如)。将线程固定到其核心看起来像:
pthread_t thread_objs[cpu_count];
pthread_attr_t attr;
cpu_set_t cpus;
pthread_attr_init(&attr);
for (unsigned int t = 0; t < cpu_count; t++) {
pthread_t new_thread;
CPU_ZERO(&cpus);
CPU_SET(t, &cpus);
if(pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus)) {
std::cerr << "fatal: could not set affinity" << std::endl;
return 1;
}
if(pthread_create(&thread_objs[t], &attr, start_routine, NULL)) {
std::cerr << "fatal: thread creation failed" << std::endl;
return 1;
}
}
for (unsigned int t = 0; t < cpu_count; t++) {
pthread_join(thread_objs[t], NULL);
}
Ẁhile测试,我发现pthread_attr_setaffinity_np
的第一次调用永远不会回来。我等了几个小时,但什么都没发生。
二手glibc
是ldd (Ubuntu GLIBC 2.23-0ubuntu9) 2.23
。
答案
下面我发布我的代码(基本上与问题中的相同),它适用于Ubuntu(实际上是Goobuntu)14和12核机器。减少nr个CPU变量以使其在具有较少内核的计算机上运行。
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using std::cerr;
using std::cout;
const int cpu_count = 12;
pthread_t thread_objs[cpu_count];
pthread_attr_t attr;
cpu_set_t cpus;
void* start_routine(void*)
{
sleep(2);
return 0;
}
int main()
{
pthread_attr_init(&attr);
for (unsigned int t = 0; t < cpu_count; t++) {
pthread_t new_thread;
CPU_ZERO(&cpus);
CPU_SET(t, &cpus);
cout << "Nr of set cpus in set: " << CPU_COUNT(&cpus) << '
';
if(pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus)) {
std::cerr << "fatal: could not set affinity" << std::endl;
return 1;
}
if(pthread_create(&thread_objs[t], &attr, start_routine, NULL)) {
std::cerr << "fatal: thread creation failed" << std::endl;
return 1;
}
}
for (unsigned int t = 0; t < cpu_count; t++) {
pthread_join(thread_objs[t], NULL);
}
cout << "Joined all threads, ending!
";
}
以上是关于pthread_attr_setaffinity_np不会返回或抛出错误的主要内容,如果未能解决你的问题,请参考以下文章