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\n",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\n",pthread_self());//获取当前线程ID
17     pthread_create(&tid,NULL,fun,NULL);
18     printf("child's tid=%lu\n",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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值