ceph bluestore源码分析:C++ 获取线程id
生活随笔
收集整理的這篇文章主要介紹了
ceph bluestore源码分析:C++ 获取线程id
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
閱讀ceph源碼過程中需要明確當前操作是由哪個線程發出,此時需要根據線程id來確認線程名稱
C++獲取線程id是通過系統調用來直接獲取
函數描述
頭文件:<sys/syscall.h>
函數名稱:syscall(SYS_gettid)
該函數直接返回了一個pid_t int類型的數字,即為當前線程id
此外函數pthread_self同樣能夠獲取線程id,但是該函數獲取到的線程id為posix的線程id,并不是真實的線程id.所以最后獲取到的數值是一個特別長的標識,并非top -Hp pid中的實際線程id
函數使用
編寫如下代碼:
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <pthread.h>
#define gettid() syscall(SYS_gettid)
using namespace std;void *threadFunc(void *p)
{printf("go into threadfunc ,pthread_self id is %d\n",pthread_self());printf("go into threadfunc ,gettid id is %d \n",gettid());int i = 0;while(1){i++;sleep(1);}return NULL;
}int main()
{printf("man thread tid is %d \n man pid is %d\n",gettid(),getpid());pthread_t id;pid_t tid;pthread_create (&id, NULL, threadFunc, NULL);pthread_create (&id, NULL, threadFunc, NULL);pthread_create (&id, NULL, threadFunc, NULL);int i=0;while (1){i++;sleep(1);}return 0;
}
運行結果如下:
[root@node1 ~]# ./a.out
man thread tid is 28244 man pid is 28244
go into threadfunc ,pthread_self id is -1511180544
go into threadfunc ,gettid id is 28245
end and get the tgkill tid is -1
go into threadfunc ,pthread_self id is -1527965952
go into threadfunc ,pthread_self id is -1519573248
go into threadfunc ,gettid id is 28246
go into threadfunc ,gettid id is 28247
同時使用命令查看得到如下輸出
[root@node1 ~]# ps -ef|grep a.out
root 28244 21581 0 09:41 pts/10 00:00:00 ./a.out
root 28902 8965 0 09:41 pts/7 00:00:00 grep --color=auto a.out
[root@node1 ~]# ps -Tp 28244 PID SPID TTY TIME CMD
28244 28244 pts/10 00:00:00 a.out
28244 28245 pts/10 00:00:00 a.out
28244 28246 pts/10 00:00:00 a.out
28244 28247 pts/10 00:00:00 a.out
命令ps -Tp pid同樣可以得到當前進程相關的信息,第二列SPID即為線程id.可以看到進程id和主線程id是一致的,同時pthread_self函數的posix 線程id并非我們實際真實的線程id
總結
以上是生活随笔為你收集整理的ceph bluestore源码分析:C++ 获取线程id的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用sigaction处理内核信号
- 下一篇: 求一个圣经中好听的名字。