如何在 C 中获取 pthread 名称

How to get a pthread name in C

假设我创建了一个 pthread 作为 pthread_t lift_3;pthread_create(&lift_1, NULL, lift, share);。当它进入 lift() 时,我怎样才能让它打印线程的实际名称?或者为线程设置一个名称?

我试过使用pthread_self()获取id,但它给出的是随机数

#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

您正在寻找 "name of the function that the thread started in"。 没有"thread name"这样的东西。 调用 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; 
}