Как получить имя pthread в C - PullRequest
3 голосов
/ 02 мая 2020

Скажем, я создаю pthread как pthread_t lift_3; и pthread_create(&lift_1, NULL, lift, share);. Когда он входит в lift(), как я могу получить функцию печати фактического имени потока? Или установить имя для потока?

Я пытался использовать pthread_self() для получения идентификатора, но вместо этого он дает случайные числа

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 
void* lift(void* ptr) 
{ 
    printf("thread name = %c\n", pthread_self()); 
    pthread_exit(NULL); 
    return NULL; 
} 

int main() 
{ 
    pthread_t lift_1; // declare thread 
    pthread_create(&lift_1, NULL, lift, NULL); 
    pthread_join(lift_1, NULL);  
    return 0; 
} 

Ожидаемый результат должен быть thread name = lift_1

1 Ответ

3 голосов
/ 02 мая 2020

Вы ищете "имя функции, в которой запущен поток". Не существует такой вещи, как «имя потока». При вызове pthread_self вы получаете «id» потока, что-то вроде случайно сгенерированного имени.

Чтобы смоделировать желаемое поведение в прошлом, я написал следующий код:

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 

// This lines means a variable that is created per-thread
__thread const char* thread_name;

void* lift(void* ptr) 
{ 
    // Paste this line in the beginning of every thread routine.
    thread_name = __FUNCTION__;

    // Note two changes in this line
    printf("thread name = %s\n", thread_name); 
    pthread_exit(NULL); 
    return NULL; 
} 

int main() 
{ 
    // Added line
    thread_name = __FUNCTION__;

    pthread_t lift_1; // declare thread 
    pthread_create(&lift_1, NULL, lift, NULL); 
    pthread_join(lift_1, NULL);  
    //Added line
    printf("Original thread name: %s\n", thread_name);
    return 0; 
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...