pthread_self() in C

The pthread_self() function in C is used to obtain the ID of the currently executing thread. This function provides a unique identifier for each running thread, allowing programs to distinguish between different threads during execution.

Syntax

pthread_t pthread_self(void);

Parameters

  • None − The function takes no parameters.

Return Value

  • Returns a pthread_t value representing the thread ID of the calling thread.
  • Thread IDs are unique among all currently existing threads, but can be reused after a thread terminates.

Example

The following example demonstrates how pthread_self() works by creating a thread and comparing thread IDs −

Note: To compile this program, use: gcc program.c -pthread

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void* func(void* p) {
    printf("From the function, the thread id = %ld<br>", (long)pthread_self());
    pthread_exit(NULL);
    return NULL;
}

int main() {
    pthread_t thread;
    
    printf("From main, main thread id = %ld<br>", (long)pthread_self());
    
    pthread_create(&thread, NULL, func, NULL);
    printf("Created thread id = %ld<br>", (long)thread);
    
    pthread_join(thread, NULL);
    return 0;
}
From main, main thread id = 140736308506944
Created thread id = 123145575014400
From the function, the thread id = 123145575014400

Key Points

  • Each thread has a unique pthread_t identifier while it exists.
  • Thread IDs can be reused after a thread terminates and is joined.
  • The main thread also has a thread ID that can be obtained using pthread_self().
  • Thread IDs should be cast to long for proper printing with %ld format specifier.

Conclusion

The pthread_self() function is essential for thread identification and debugging in multithreaded C programs. It provides a reliable way to distinguish between different threads during program execution.

Updated on: 2026-03-15T10:38:47+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements