Friday, October 5, 2018

Pthread - thread id

When a thread is created using pthread_create(), a unique thread ID is assigned to the newly created thread. This thread ID is used by other thread functions to identify the thread. pthread_self() function returns the same id of the thread.
man 3 pthread_self
man 3 pthread_create
For pthread_create(), the first argument is of type pthread_t. It is assigned with the ID of the newly created thread. The abstract type of pthread_t is implementation dependent. It may be int, unsigned long int or in some implementation a structure having information about the thread.

A snippet from the man page of pthread_create.
Before returning, a successful call to pthread_create() stores the ID of the new thread in the buffer pointed to by thread; this identifier is used to refer to the thread in subsequent calls to other pthread functions.
pthread_self returns the same ID, what pthread_create stores in the first argument "thread"
       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
       pthread_t pthread_self(void);
In my system pthread_t type is "unsigned long int"
/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h:typedef unsigned long int pthread_t;
In the following example, the value returned by pthread_self() and th1 are same.
// main function:
    pthread_t th1;

    if(rc1 = pthread_create(&th1, NULL, &functionC1, NULL))
    {
           printf("Thread creation failed, return code %d, errno %d", rc1, errno);
    }
    printf("Printing thread id %lu\n", th1);

// Thread function: 
    void *functionC1(void *)
    {
            printf("In thread function Printing thread id %lu\n", pthread_self());
    }

    Output:
    Printing thread id 140429554910976
    In thread function Printing thread id 140429554910976

No comments:

Post a Comment