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 
 6 void* fun(void* p)
 7 {
 8     printf("child thread id=%lu
",pthread_self());//获取当前线程ID
 9     //sleep(100);
10     return NULL;
11 }
12 
13 int main(int argc,char* argv[])
14 {
15     pthread_t tid;
16     printf("main thread id=%lu
",pthread_self());//获取当前线程ID
17     pthread_create(&tid,NULL,fun,NULL);
18     printf("child's tid=%lu
",tid);
19     sleep(100); //wait child
20     return 0;
21 }

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

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

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

$ ps -efL|grep a.out
UID        PID  PPID   LWP  C NLWP STIME TTY          TIME CMD
ubuntu   17693 17387 17693  0    2 17:06 pts/4    00:00:00 ./a.out
ubuntu   17693 17387 17694  0    2 17:06 pts/4    00:00:00 ./a.out
原文地址:https://www.cnblogs.com/zhaojk2010/p/5127831.html