Chinaunix

标题: linux多线程环境下gettid pthread_self 那个函数获得线程ID [打印本页]

作者: tianhailong    时间: 2013-09-04 01:11
标题: linux多线程环境下gettid pthread_self 那个函数获得线程ID


linux多线程环境下gettid() pthread_self() 两个函数都获得线程ID
linux使用进程模拟线程,gettid 函数返回实际的进程ID
pthread_self 函数返回 pthread_create创建线程时的ID,
我就有点迷惑,
到底那个是线程的ID呢,一个线程不能有两个ID吧

我测试 pthread_self 函数返回的是一个地址,例如:
pid 967--tid 967--  pthread_self b7f5c6c0

请大家答疑解惑了
作者: weishuo1999    时间: 2013-09-04 09:06
gettid是内核中的线程的ID, pthread_self是POSIX thread ID
作者: myworkstation    时间: 2013-09-04 10:09
weishuo1999 发表于 2013-09-04 09:06
gettid是内核中的线程的ID, pthread_self是POSIX thread ID


2楼说的对,线程库实际上由两部分组成:内核的线程支持+用户态的库支持(glibc),Linux在早期内核不支持线程的时候glibc就在库中(用户态)以纤程(就是用户态线程)的方式支持多线程了,POSIX thread只要求了用户编程的调用接口对内核接口没有要求。linux上的线程实现就是在内核支持的基础上以POSIX thread的方式对外封装了接口,所以才会有两个ID的问题。
作者: tianhailong    时间: 2013-09-04 10:39
这就有个问题,我们知道一个进程ID唯一的标识一个进程,
但是对一个线程有两个ID,
以那个为准呢?回复 3# myworkstation


   

作者: myworkstation    时间: 2013-09-04 11:33
回复 4# tianhailong


    POSIX thread ID可以在一个进程内唯一标识一个线程,但如果放到系统范围内的话就得用gettid了。
作者: tianhailong    时间: 2013-09-04 12:22
使用gettid得到的是系统内唯一的线程标识,自然可以在一个进程内唯一标识那么我们干嘛需要用 POSIX thread ID 呢回复 5# myworkstation


作者: myworkstation    时间: 2013-09-04 12:31
回复 6# tianhailong


    gettid是不可移植的。如果你换到别的系统上如何来保证程序的可移植性呢?除非你的程序只在linux上跑。
作者: linux_c_py_php    时间: 2013-09-04 12:38
gettid返回的id相当于进程id, 可以gdb -p连接上去, 也可以top -H/ps -Lef看到线程状态.
作者: tianhailong    时间: 2013-09-04 12:41
明白了,其实 POSIX thread ID 是POSIX 标准的,所有遵循POSIX标准的系统都支持,
gettid是linux独有的,
但是如果在linux环境下开发, POSIX thread ID
就是多余的了吧,
那么 gettid 与 POSIX thread ID 有什么对应关系吗?
回复 7# myworkstation


作者: myworkstation    时间: 2013-09-04 13:25
回复 9# tianhailong

由于在Linux下POSIX thread 和系统thread是一对一的模型,所以可以认为一个gettid必然对应一个pthread id,但没有什么方法直接实现对两者的对应转换。
   
作者: tianhailong    时间: 2013-09-04 21:19
那在linux环境下,调试线程其实使用的也是 gettid的返回,
POSIX thread ID 没有 关系,
可以认为在linux环境下,POSIX thread ID 没有实际用处吗?
回复 10# myworkstation


   
作者: myworkstation    时间: 2013-09-05 10:06
回复 11# tianhailong


    pthread_detach,pthread_cancel等函数是需要POSIX thread id为参数的。怎么能说没有用呢。
作者: xwhbwas2008    时间: 2013-09-05 10:09
http://bbs.chinaunix.net/thread-2314614-1-1.html 多年未上  看到熟悉的帖子





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2