Linux C獲取線程ID

頭文件

#include <pthread.h>

函數原型

pthread_t pthread_self(void);
函數做用:得到線程自身的ID。pthread_t的類型爲unsigned long int,因此在打印的時候要使用%lu方式,不然將產生奇怪的結果。

功能

獲取當前調用線程的 thread identifier(標識號). ide

#include <stdio.h>
int main()
{
    pid_t pid;
    pthread_t tid;
    pid = getpid();
    tid = pthread_self();
    printf("pid %u tid %u (0x%x)\n", (unsigned int)pid,
                (unsigned int)tid, (unsigned int)tid); /* tid是unsigned long int,這裏只是方便轉換 */
    return 0;
}
 
編譯:
$ gcc thread.c -o thread -lpthread
相關文章
相關標籤/搜索