How to get a pthread name in C

Zam-Oxy

Say I create a pthread as pthread_t lift_3; and pthread_create(&lift_1, NULL, lift, share);. When it goes into lift(), how can I get it the function to print the actual name of the thread? Or set a name for the thread?

I have tried using pthread_self() to acquire the id, but it instead gives random numbers

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

The expected outcome should be thread name = lift_1

NadavS

You're looking for the "name of the function that the thread started in". There is no such thing as "thread name". When calling pthread_self, you get the "id" of the thread, which something like a randomly-generated name.

To simulate the desired behavior in the past, I wrote the following code:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related