
正文
linux获取线程ID
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
pthread_self()获取当选线程的ID。
这个ID与pthread_create的第一个参数返回的相同。
但是与ps命令看到的不同,因此只能用于程序内部,用于对线程进行操作。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h> void* fun(void* p)
{
printf("child thread id=%lu\n",pthread_self());//获取当前线程ID
//sleep(100);
return NULL;
} int main(int argc,char* argv[])
{
pthread_t tid;
printf("main thread id=%lu\n",pthread_self());//获取当前线程ID
pthread_create(&tid,NULL,fun,NULL);
printf("child's tid=%lu\n",tid);
sleep(); //wait child
return ;
}
编译运行一下,观察输出,这个ID与pthread_create的第一个参数返回的相同
$ gcc threadid.c -lpthread
$ ./a.out
main thread id=
child's tid=
child thread id=
但是与ps看到的结果是不同的,不是一回事(我去掉了无关输出)
$ ps -efL|grep a.out
UID PID PPID LWP C NLWP STIME TTY TIME CMD
ubuntu : pts/ :: ./a.out
ubuntu : pts/ :: ./a.out








