如何在C中获得pthread名称

问题描述 投票:1回答:1

假设我创建一个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

c pthreads
1个回答
3
投票

您正在寻找“线程在其中开始的函数的名称”。没有“线程名”之类的东西。调用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; 
} 
© www.soinside.com 2019 - 2024. All rights reserved.