The structure of pthread is as follows. It is taken from https://stuff.mit.edu/afs/sipb/project/pthreads/include/pthread.h
struct pthread {
struct machdep_pthread machdep_data;
enum pthread_state state;
pthread_attr_t attr;
/* Signal interface */
sigset_t sigmask;
sigset_t sigpending;
/* Time until timeout */
struct timespec wakeup_time;
/* Cleanup handlers Link List */
struct pthread_cleanup *cleanup;
/* Join queue for waiting threads */
struct pthread_queue join_queue;
/* Queue thread is waiting on, (mutexes, cond. etc.) */
struct pthread_queue *queue;
/*
* Thread implementations are just multiple queue type implemenations,
* Below are the various link lists currently necessary
* It is possible for a thread to be on multiple, or even all the
* queues at once, much care must be taken during queue manipulation.
*
* The pthread structure must be locked before you can even look at
* the link lists.
*/
struct pthread *pll; /* ALL threads, in any state */
/* struct pthread *rll; Current run queue, before resced */
struct pthread *sll; /* For sleeping threads */
struct pthread *next; /* Standard for mutexes, etc ... */
/* struct pthread *fd_next; For kernel fd operations */
int fd; /* Used when thread waiting on fd */
semaphore lock;
/* Data that doesn't need to be locked */
void *ret;
int error;
const void **specific_data;
};
typedef struct pthread * pthread_t;
Now let's see the following code to print the ID of the thread:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* calls(void* ptr)
{
// using pthread_self() get current thread id
printf("In function \nthread id = %ld\n", pthread_self());
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t thread; // declare thread
pthread_create(&thread, NULL, calls, NULL);
printf("In main \nthread id = %ld\n", thread);
pthread_join(thread, NULL);
return 0;
}
Output in my system is:
In main
thread id = 140289852200704
In function
thread id = 140289852200704
From pthread.h file (above), pthread is a structure, thread
in the code is a pointer to the structure pthread (since pthread_t
is typdef struct pthread*
). Why does printing this pointer gives us the thread ID?