閱讀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