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
", getpid(), (long int)syscall(__NR_gettid), pthread_self());
    int ret = fork();
    if(ret == 0){
        printf("[child] pid: %d, tid:%ld, self: %ld
", getpid(), (long int)syscall(__NR_gettid), pthread_self());
    }else if(ret > 0){
        printf("[parent] pid: %d, tid:%ld, self: %ld
", 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的问题。

原文地址:https://www.cnblogs.com/luntai/p/6184156.html