linux 获取 当前线程id 和 当前线程名称
g++ -g t.cpp && ./a.out
#111106
#a.out
// filename : t.cpp
#include <stdio.h>
#include <pthread.h>
#include <syscall.h>
#include <unistd.h>
#define PTHREAD_NAME_LIMIT 256
#ifndef _EMPTYY_
#define _EMPTYY_ '\0'
#endif
void getPThreadName(pid_t tId,char * thread_name){
//pthread_self 也是获取当前线程, 但是返回和 "获取线程id syscall(SYS_gettid) " 的返回 貌似对不上, 这里需要后面学习一下
pthread_t pthread=pthread_self();
// char thread_name[MAX_LENGTH_PTHREAD_NAME];
const int hasError = pthread_getname_np(pthread, thread_name, PTHREAD_NAME_LIMIT);
// return !getname_rv;
if (hasError) {
//error
// 出错时, 结尾有可能没有 \0, 所以添加 \0 以防止使用处意外
thread_name[PTHREAD_NAME_LIMIT-1]=_EMPTYY_;
return;
}
}
static pid_t myGetThreadId(void)
{
//获取线程id
return syscall(SYS_gettid);
}
int main(int argc,char ** args){
char threadName[PTHREAD_NAME_LIMIT];
pid_t threadIdOut=myGetThreadId();
printf("%d\n",threadIdOut);
getPThreadName(threadIdOut,threadName);
printf("%s\n",threadName);
return 0;
}