3

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

Zam-Oxy
  • 130
  • 10
  • 1
    `lift_1` is the name of a variable, an internal symbol that doesn't exists at runtime. Thread are identified by ids (roughly numbers). Have a look at https://stackoverflow.com/questions/21091000/how-to-get-thread-id-of-a-pthread-in-linux-c-program and https://stackoverflow.com/questions/9221939/private-variables-in-threads – Jean-Baptiste Yunès May 02 '20 at 07:36

1 Answers1

3

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; 
} 
NadavS
  • 779
  • 3
  • 12
  • `__FUNCTION__` is a GNU extension kept for (very old) backward compatibility. Use `__func__`. – KamilCuk May 02 '20 at 08:12
  • That code works fine, but `thread_name` should be inside `pthread_create` as an argument rather than a global variable. – Zam-Oxy May 02 '20 at 08:20
  • 1
    "There is no such thing as "thread name"" -- on some platforms, there _is_. http://man7.org/linux/man-pages/man3/pthread_setname_np.3.html – Employed Russian May 02 '20 at 14:26
  • good to know! To be fair, `pthread_set_name` is probably implemented using my solution. – NadavS May 02 '20 at 14:46