解决不同进程下,线程id相同情况无法通信的问题
在linux下每一个进程都一个进程id,类型`pid_t`,可以由 `getpid()`获取。<br /> POSIX线程也有线程id,类型`pthread_t`,可以由 `pthread_self()`获取,线程id由线程库维护。<br /> 但是各个进程独立,所以会有不同进程中线程号相同节的情况。
那么这样就会存在一个问题,我的进程p1中的线程pt1要与进程p2中的线程pt2通信怎么办?
进程id不可以,线程id又可能重复,所以这里会有一个真实的线程id唯一标识,tid。glibc没有实现gettid的函数,所以我们可以通过linux下的系统调用syscall(SYS_gettid)来获得。
测试代码如下:
#include <stdio.h>#include <pthread.h>#include <sys/types.h>#include <sys/syscall.h>#include <unistd.h>void *hello(void *s){printf("%s()\t, line = %d\t, getpid() = %#x\n",__FUNCTION__,__LINE__,getpid());printf("%s()\t, line = %d\t, pthread_self() = %#x\t, SYS_gettid = %#x\n",__FUNCTION__,__LINE__,pthread_self(),syscall(SYS_gettid));}int main(){printf("%s()\t, line = %d\t, getpid() = %#x\n",__FUNCTION__,__LINE__,getpid());printf("%s()\t, line = %d\t, pthread_self() = %#x\t, SYS_gettid = %#x\n",__FUNCTION__,__LINE__,pthread_self(),syscall(SYS_gettid));pthread_t thread_id;pthread_create(&thread_id,NULL,hello,NULL);pthread_join(thread_id,NULL);return 0;}

结论:
**getpid()**得到的是进程的**pid**,在内核中,每个线程都有自己的**PID**,要得到线程的**PID**(即TID),必须用**syscall(SYS_gettid);****pthread_self()**获取的是线程ID,仅在同一个进程中保证唯一- 注意到:在
**main**函数中,**getpid**的值与**syscall(SYS_gettid)**的值相同,而在**pthread_self()**则不同,也验证了上述观点 
