getpid 與 gettid 與 pthread_self


獲取進程的PIDprocess ID)

 

#include <unistd.h>  
pid_t getpid(void); 

 

 

 

獲取線程的TID(thread ID)

1)gettid或者類似gettid的方法  :獲取內核中真實的線程ID

2)直接調用pthread_self() : posix描述的線程ID。

  在POSIX線程庫下每一線程也有一個ID,類型pthread_t,就是通過pthrea_self()得到的。該ID由線程庫維護,每一個進程下的線程ID可能相同。

  Linux下POSIX線程庫實現的線程其實也是一個進程(LWP),該進程與main(啟動線程的進程)共享一些資源,比如代碼段、數據段等。

詳細:

  man一下gettid得到如下結果:

NAME
       gettid - get thread identification

SYNOPSIS
       #include <sys/types.h>

       pid_t gettid(void);

       Note: There is no glibc wrapper for this system call; see NOTES.

DESCRIPTION
       gettid()  returns  the  caller's thread ID (TID).  In a single-threaded
       process, the thread ID is equal to the process ID (PID, as returned  by
       getpid(2)).  In a multithreaded process, all threads have the same PID,
       but each one has a unique TID.  For further details, see the discussion
       of CLONE_THREAD in clone(2).

  gettid返回調用者的線程ID;在單線程的進程中,tid=pid(線程id),在多線程進程中,不同的線程,所有的線程又相同的pid。

  man一下pthread_self:

SYNOPSIS
       #include <pthread.h>

       pthread_t pthread_self(void);

       Compile and link with -pthread.

DESCRIPTION
       The pthread_self() function returns the ID of the calling thread.  This
       is the same value that is returned in *thread in the  pthread_create(3)
       call that created this thread.

  pthread_self返回的是posix定義的線程ID,與內核tid不同。作用是可以用來區分同一進程中不同的線程。

++ pthread

  pthread是POSIX線程(POSIX threads)簡稱pthread,是線程的POSIX標准。該標准定義了創建和操縱線程的一整套API。

轉:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
//#include <sys/syscall.h> 

#define __NR_gettid 186
void *f()
{
    int status;
    printf("begin: pid: %d, tid:%ld, self: %ld\n", getpid(), (long int)syscall(__NR_gettid), pthread_self());
    int ret = fork();
    if(ret == 0){
        printf("[child] pid: %d, tid:%ld, self: %ld\n", getpid(), (long int)syscall(__NR_gettid), pthread_self());
    }else if(ret > 0){
        printf("[parent] pid: %d, tid:%ld, self: %ld\n", getpid(), (long int)syscall(__NR_gettid), pthread_self());
        waitpid(-1, &status, 0);
    }
}

int main()
{
    
    int i = 0;
    pthread_t pth[1]; 
    while(i++<1){
        pthread_create(&pth[i], NULL, f, NULL);
        sleep(1);
    }
    pause();
}

 

So Why? 有兩個進程ID(thread ID)

  描述線程的id,為什么需要兩個不同的ID呢?這是因為線程庫實際上由兩部分組成:內核的線程支持+用戶態的庫支持(glibc),Linux在早 期內核不支持線程的時候glibc就在庫中(用戶態)以纖程(就是用戶態線程)的方式支持多線程了,POSIX thread只要求了用戶編程的調用接口對內核接口沒有要求。

  linux上的線程實現就是在內核支持的基礎上以POSIX thread的方式對外封裝了接口,所以才會有兩個ID的問題。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM