2017-06-27 89 views
0
#include<stdio.h> 
#include<unistd.h> 
#include<pthread.h> 
#include<sys/types.h> 
int main(){ 
    int systid=syscall(186); 
    int pt_tid=pthread_self(); 
    pid_t id=getpid(); 
    printf("pid=%d,tid=%d,pt_tid=%d\n",id,systid,pt_tid); 
    return 0; 
} 

我在RHEL 5上用gcc4.1.2运行这个程序。pthread_self()不返回有意义的线程ID?

$gcc testtid.c -lpthread && ./a.out 
pid=35086,tid=35086,pt_tid=1295541984 

似乎能系统调用给出正确的线程ID(同样喜欢进程ID),但pthread_self没有给出有意义的结果。

是否因为pthread_self不可移植?

+2

该值唯一标识线程。它不打算以任何其他方式有意义。特别是它不一定等于任何内核损坏的标识符。 –

+0

所以,你的意思是它并不表示任何“linux”上下文值,仅用于POSIX可移植性,对吧? –

+0

是的,就是这个。 –

回答

1

如果你读man pthread_self,你应该:

线程标识符应被视为不透明:任何试图在并行线程调用使用其他线程ID比是不可移植的,并可能导致不确定的结果。

线程ID保证只在一个进程内唯一。线程ID可以在终止的线程连接后重用,或者分离的线程终止。

pthread_self()返回的线程标识与调用gettid(2)返回的内核线程标识不同。

相关问题