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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21091000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:50:19  来源:igfitidea点击:

how to get thread id of a pthread in linux c program?

clinuxpthreads

提问by Ravi Chandra

In linux c program, how to print thread id of a thread created by pthread library?
for ex: we can get pid of a process by getpid()

在linux c程序中,如何打印pthread库创建的线程的线程ID?
例如:我们可以通过以下方式获取进程的 pidgetpid()

采纳答案by Abhitesh khatri

pthread_self()function will give the thread id of current thread.

pthread_self()函数将给出当前线程的线程 id。

pthread_t pthread_self(void);

The pthread_self()function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np()to return an integral identifier for the thread.

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

NOTE:

笔记:

pthread_id_np_t   tid;
tid = pthread_getthreadid_np();

is significantly faster than these calls, but provides the same behavior.

比这些调用快得多,但提供相同的行为。

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

回答by Jeff

You can use pthread_self()

您可以使用 pthread_self()

The parent gets to know the thread id after the pthread_create()is executed sucessfully, but while executing the thread if we want to access the thread id we have to use the function pthread_self().

父进程在pthread_create()成功执行后会知道线程 id ,但是在执行线程时,如果我们想访问线程 id,我们必须使用函数pthread_self()

回答by bleater

As noted in other answers, pthreads does not define a platform-independent way to retrieve an integral thread ID.

正如其他答案中所述,pthreads 没有定义一种独立于平台的方式来检索完整的线程 ID。

On Linux systems, you can get thread ID thus:

在 Linux 系统上,您可以通过以下方式获取线程 ID:

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

On many BSD-based platforms, this answer https://stackoverflow.com/a/21206357/316487gives a non-portable way.

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

However, if the reason you think you need a thread ID is to know whether you're running on the same or different thread to another thread you control, you might find some utility in this approach

但是,如果您认为需要线程 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");

If you just need to know if you're on the main thread, there are additional ways, documented in answers to this question how can I tell if pthread_self is the main (first) thread in the process?.

如果您只需要知道您是否在主线程上,还有其他方法,记录在这个问题的答案中,我如何判断 pthread_self 是否是进程中的主(第一个)线程?.

回答by Evan Langlois

What? The person asked for Linux specific, and the equivalent of getpid(). Not BSD or Apple. The answer is gettid() and returns an integral type. You will have to call it using syscall(), like this:

什么?该人要求特定于 Linux,相当于 getpid()。不是 BSD 或苹果。答案是 gettid() 并返回一个整数类型。您必须使用 syscall() 调用它,如下所示:

#include <sys/types.h>
#include <sys/syscall.h>

 ....

 pid_t x = syscall(__NR_gettid);

While this may not be portable to non-linux systems, the threadid is directly comparable and very fast to acquire. It can be printed (such as for LOGs) like a normal integer.

虽然这可能无法移植到非 linux 系统,但 threadid 可以直接比较并且获取速度非常快。它可以像普通整数一样打印(例如用于 LOG)。

回答by nandan

This single line gives you pid , each threadid and spid.

这一行为您提供了 pid 、每个线程 ID 和 spid。

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

回答by nandan

pthread_getthreadid_npwasn't on my Mac os x. pthread_tis an opaque type. Don't beat your head over it. Just assign it to void*and call it good. If you need to printfuse %p.

pthread_getthreadid_np不在我的 Mac os x 上。 pthread_t是不透明的类型。不要为它打头阵。只需将其分配给void*并称其为好。如果您需要printf使用%p.

回答by Weiqi Gu

pid_t tid = syscall(SYS_gettid);

Linux provides such system call to allow you get id of a thread.

Linux 提供了这样的系统调用来允许您获取线程的 id。

回答by emre can

There is also another way of getting thread id. While creating threads with

还有另一种获取线程ID的方法。在创建线程时

int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

function call; the first parameter pthread_t * threadis actually a thread id (that is an unsigned long int defined in bits/pthreadtypes.h). Also, the last argument void *argis the argument that is passed to void * (*start_routine)function to be threaded.

函数调用;第一个参数pthread_t * thread实际上是一个线程 id(即在 bits/pthreadtypes.h 中定义的一个无符号长整型)。此外,最后一个参数void *arg是传递void * (*start_routine)给要线程化的函数的参数 。

You can create a structure to pass multiple arguments and send a pointer to a structure.

您可以创建一个结构来传递多个参数并发送一个指向结构的指针。

typedef struct thread_info {
    pthread_t thread;
    //...
} thread_info;
//...
tinfo = malloc(sizeof(thread_info) * NUMBER_OF_THREADS);
//...
pthread_create (&tinfo[i].thread, NULL, handler, (void*)&tinfo[i]);
//...
void *handler(void *targs) {
    thread_info *tinfo = targs;
    // here you get the thread id with tinfo->thread
}

回答by Oleg Oleg

Platform-independent way (starting from c++11) is:

独立于平台的方式(从 c++11 开始)是:

#include <thread>

std::this_thread::get_id();

回答by snr

I think not only is the question not clear but most people also are not cognizant of the difference. Examine the following saying,

我认为不仅问题不清楚,而且大多数人也没有意识到差异。考查以下说法,

POSIX thread IDs are not the same as the thread IDs returned by the Linux specific gettid()system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid()is a number (similar to a process ID) that is assigned by the kernel. Although each POSIX thread has a unique kernel thread ID in the Linux NPTL threading implementation, an application generally doesn't need to know about the kernel IDs (and won't be portable if it depends on knowing them).

Excerpted from: The Linux Programming Interface: A Linux and UNIX System Programming Handbook, Michael Kerrisk

POSIX 线程 ID 与 Linux 特定gettid()系统调用返回的线程 ID 不同。POSIX 线程 ID 由线程实现分配和维护。返回的线程IDgettid()是内核分配的一个数字(类似于进程ID)。尽管每个 POSIX 线程在 Linux NPTL 线程实现中都有一个唯一的内核线程 ID,但应用程序通常不需要知道内核 ID(并且如果它依赖于知道它们,则不会是可移植的)。

摘自:Linux 编程接口:Linux 和 UNIX 系统编程手册,Michael Kerrisk

IMHO, there is only one portable way that pass a structure in which define a variable holding numbers in an ascending manner e.g. 1,2,3...to per thread. By doing this, threads' id can be kept track. Nonetheless, int pthread_equal(tid1, tid2)function should be used.

恕我直言,只有一种可移植的方式传递结构,其中以升序方式定义变量保存数字,例如1,2,3...每个线程。通过这样做,可以跟踪线程的 id。尽管如此,int pthread_equal(tid1, tid2)应该使用函数。

if (pthread_equal(tid1, tid2)) printf("Thread 2 is same as thread 1.\n");
else printf("Thread 2 is NOT same as thread 1.\n");