pthread_attr_setaffinity_np不会返回或抛出错误

时间:2017-12-19 14:00:21

标签: c++ pthreads

我正在尝试启动几个线程,每个线程都有自己的核心(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的第一次调用永远不会返回。我等了几个小时,但什么也没发生。

已使用glibcldd (Ubuntu GLIBC 2.23-0ubuntu9) 2.23

1 个答案:

答案 0 :(得分:1)

下面我发布我的代码(基本上与问题中的相同),它适用于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) << '\n';

        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!\n";
}