如何在linux c程序中获得pthread的线程ID?

在linux的c程序中,如何打印由pthread库创build的线程的线程ID?
例如:我们可以通过getpid()获得一个进程的PID,

pthread_self()函数会给出当前线程的线程ID。

 pthread_t pthread_self(void); 

pthread_self()函数返callback用线程的Pthread句柄。 pthread_self()函数不返callback用线程的整数线程。 您必须使用pthread_getthreadid_np()返回线程的整数标识符。

注意:

 pthread_id_np_t tid; tid = pthread_getthreadid_np(); 

比这些调用显着更快,但是提供了相同的行为。

 pthread_id_np_t tid; pthread_t self; self = pthread_self(); pthread_getunique_np(&self, &tid); 

什么? 这个人要求Linux具体,相当于getpid()。 不BSD或苹果。 答案是gettid()并返回一个整数types。 您将不得不使用syscall()来调用它,如下所示:

 #include <sys/types.h> #include <sys/syscall.h> .... pid_t x = syscall(__NR_gettid); 

虽然这可能不能移植到非Linux系统,但是threadid可以直接比较并且非常快速地获取。 它可以像正常整数一样打印(如LOG)。

你可以使用pthread_self()

在成功执行pthread_create()之后,父进程知道线程ID,但是如果要访问线程ID,则在执行线程时,必须使用函数pthread_self()

正如在其他答案中指出的那样,pthreads没有定义一个独立于平台的方式来检索一个完整的线程ID。

在Linux系统上,您可以获得线程ID:

 #include <sys/types.h> pid_t tid = gettid(); 

在许多基于BSD的平台上,这个答案https://stackoverflow.com/a/21206357/316487给出了一种不可移植的方式。;

然而,如果你认为你需要一个线程ID的原因是要知道你是否在相同或不同的线程上运行到另一个你控制的线程,你可能会发现这种方法

 static pthread_t threadA; // On thread A... threadA = pthread_self(); // On thread B... pthread_t threadB = pthread_self(); if (pthread_equal(threadA, threadB)) printf("Thread B is same as thread A.\n"); else printf("Thread B is NOT same as thread A.\n"); 

如果你只是需要知道你是否在主线程中,还有其他方法,logging在这个问题的答案中, 我怎么能告诉pthread_self是否是主进程中的第一个线程呢? 。

这一行给你的PID,每个线程和spid。

  printf("before calling pthread_create getpid: %d getpthread_self: %lu tid:%lu\n",getpid(), pthread_self(), syscall(SYS_gettid)); 

pthread_getthreadid_np不在我的Mac OS x上。 pthread_t是一个不透明的types。 不要揍你的头 只要将其分配给void*并称之为好。 如果你需要printf使用%p

 pid_t tid = syscall(SYS_gettid); 

Linux提供了这样的系统调用来让你得到一个线程的id。