当前位置:首页 > 操作系统 > Linux

linux获取线程ID

pthread_self()获取当选线程的ID。
这个ID与pthread_create的第一个参数返回的相同。
但是与ps命令看到的不同,因此只能用于程序内部,用于对线程进行操作。

             1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <pthread.h>
 5 6void* fun(void* p)
 7{
 8     printf("child thread id=%lun",pthread_self());//获取当前线程ID
 9//sleep(100);10return NULL;
11}
1213int main(int argc,char* argv[])
14{
15    pthread_t tid;
16     printf("main thread id=%lun",pthread_self());//获取当前线程ID17     pthread_create(&tid,NULL,fun,NULL);
18     printf("child‘s tid=%lun",tid);
19     sleep(100); //wait child20return0;
21 }

编译运行一下,观察输出,这个ID与pthread_create的第一个参数返回的相同

$ gcc threadid.c -lpthread
$ ./a.out 
main thread id=3069878272
childs tid=3068613728
child thread id=3068613728

但是与ps看到的结果是不同的,不是一回事(我去掉了无关输出)

$ ps -efL|grep a.out
UID        PID  PPID   LWP  C NLWP STIME TTY          TIME CMD
ubuntu   1769317387176930217:06 pts/400:00:00 ./a.out
ubuntu   1769317387176940217:06 pts/400:00:00 ./a.out

 

原文:http://www.cnblogs.com/zhaojk2010/p/5127831.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!