2017-12-19 22 views
-1

두 개의 스레드를 시작하려고합니다. 각 스레드는 자체 코어 (예 : 4 코어 -> 4 스레드)입니다.pthread_attr_setaffinity_np가 반환하지 않거나 오류를 throw하지 않습니다.

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); 
} 

동안 테스트, 내가 pthread_attr_setaffinity_np의 첫 번째 호출은 결코 반환하지 않습니다 것을 알아 낸 그들의 코어 핀에게 스레드처럼 보인다. 몇 시간을 기다렸지 만 아무 일도 없었습니다.

glibcldd (Ubuntu GLIBC 2.23-0ubuntu9) 2.23입니다.

+0

첫 번째 호출은 cpu 0으로 사용자 선호도를 설정해야합니다. 맞습니까? 더 높은 우선 순위로 다른 항목이 이미 실행 중입니까? cgroup에서 이것을 실행하고 있습니까? 일정 및 선호도에 영향을 미칠 수있는 다른 요소는 무엇입니까? 전화가 돌아 오지 않는 경우 아마도 스레드가 더 이상 예약되지 않을 것입니다 ... – Useless

+0

게시 된 스 니펫은 메인 스레드에서 호출됩니다.이 스레드는 각 스레드마다 다른 스레드를 생성합니다. 스케줄링 및 선호도에 영향을 미칠 수있는 다른 스레드는 없습니다. 호출 스레드를 왜 다시 예약하지 않아야합니까? – jagemue

+0

FWIW, 우분투 14에서 작동합니다. 12 코어가 있으며, cpu_count가 13보다 낮 으면 모든 것이 좋습니다. cpu_count를 12 이상으로 늘리면 pthread_create가 실패합니다 (친화력이 존재하지 않는 CPU로 설정 되었기 때문에). –

답변

1

아래 코드는 (기본적으로 질문과 동일합니다.) 우분투 (실제로 Goobuntu)에서 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"; 
}