gettid()和pthread_self()的區別

Linux中,每個線程有一個tid,類型long,由sys_gettid()取得。

Linux內核中並沒有實現線程,而是由glibc線程庫實現的POSIX線程。每個線程也有一個id,類型 pthread_t(unsigned long int),由pthread_self()取得,該id由線程庫維護,其id空間是各個進程獨立的(即不同進程中的線程可能有相同的id)。Linux中的POSIX線程庫實現的線程在內核中看來也是一個輕量級進程(LWP),但是該進程與主進程(啓動線程的進程)共享一些資源,比如代碼段,數據段等。

1. gettid()是linux內核實現的函數,在內核看來任何線程也是一個輕量級進程,從下面內核實現的sys_gettid看來,gettid()返回的是內核管理的輕量級進程的進程id。

/* Thread ID - the internal kernel "pid" */
asmlinkage long sys_gettid(void)
{
    return current->pid;
}

2. pthread_self()在glibc中X86_64平臺的實現如下:

pthread_t __pthread_self (void)
{
    return (pthread_t) THREAD_SELF;
}

/* Return the thread descriptor for the current thread.

The contained asm must *not* be marked volatile since otherwise
assignments like
pthread_descr self = thread_self();
do not get optimized away. */
# define THREAD_SELF \
    ({ struct pthread *__self; \
    asm ("movq %%fs:%c1,%q0" : "=r" (__self) \
        : "i" (offsetof (struct pthread, header.self))); \
        __self;})

從上面代碼我們可以知道__pthread_self 得到實際上是線程描述符pthread 指針地址。

從上面我們可以得知,gettid()是內核給線程(輕量級進程)分配的進程id,全局(所有進程中)唯一;pthread_self()是在用戶態實現的,獲取的id實際上是主線程分配給子線程的線程描述符的地址而已,只是在當前進程空間中是唯一的。

轉載自:https://www.cnblogs.com/jaydenhpj/p/5200062.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章