pthread_self() ใช้ดึง ID ของ thread ปัจจุบัน ระบุ thread ที่มีอยู่ได้อย่าง unique แต่ถ้ามีหลาย threads และ thread หนึ่งจบ ID นั้นอาจถูก reuse ดังนั้น running threads ทั้งหมด IDs จะ unique
ตัวอย่าง
#include <stdio.h> #include <stdlib.h> #include <pthread.h> void* func(void* p) { printf("From the function, the thread id = %d\n", pthread_self()); pthread_exit(NULL); return NULL; } main() { pthread_t thread; pthread_create(&thread, NULL, func, NULL); printf("From the main function, the thread id = %d\n", thread); pthread_join(thread, NULL); }ผลลัพธ์
From the main function, the thread id = 1 From the function, the thread id = 1