Linux thread get thread id

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

In a Linux C program, how do I print the thread id of a thread created by the pthread library? For example like how we can get pid of a process by getpid() .

12 Answers 12

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:

#include #include #include . 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.

The person asked about something that worked on Linux. Doing so in a portable way seems to me like the preferable way to do it. If portability doesn’t count for anything then I guess Linux is really becoming the new Windows.

@Jasper Siepkes You are missing the point. He asked for a LINUX call that was the equivalent of getpid() for threads. That is gettid(). The question didn’t ask about portability or POSIX. Too many people want to show off and try and teach rather than asking the question as asked. pthread_self() does not return the kernel thread id and it not manipulatable in a way that makes for easy printing. Also, pthread_self is likely a pointer and should not be manipulated, only compared with pthread_equal(). The question asked for an ID you can print, and that’s gettid().

@EvanLanglois He’s working with the pthread library, literally the POSIX thread library. Making a POSIX compatible answer not that weird. «He asked for a LINUX call that was the equivalent of getpid() for threads.» No, getpid() was given as an example. It didn’t say the semantics were a hard specification. Making people aware of doing things in a POSIX compatible way so other communities besides Linux (like FreeBSD, Illumos, OS X, etc.) can benefit from them is not «showing off». Like I said I guess Linux has really become the next Windows.

On Linux Ubuntu 18.04 with gcc —version gcc (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0 I had to also add #define _GNU_SOURCE above all of the includes in order for syscall() to be defined. I learned that from the example at the bottom of this documentation here: man7.org/linux/man-pages/man2/syscall.2.html.

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

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_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); 

The original question was about Linux. Linux does not include the _np functions. (It doesn’t include their man pages, I didn’t check any further than that.)

Читайте также:  Где файловая система linux

@Bleater Can you please provide the official documentation for pthread_threadid_np . Am in need to use for a project, so need to check on the reliability of that API in iOS and OSX platforms. Referred the link at opensource.apple.com/source/Libc/Libc-583/pthreads/pthread.h but not sure if they are the right one.

@Trade-IdeasPhilip — To clarify, _np means non-portable. Linux has its own _np stuff, but it doesn’t include Apple’s pthread_getthreadid_np .

Some important note: A pthread_t is a kind of pointer in Linux. So if you run the same program multiple times, you may see the same pthread_t , while the actual threads are different. Thus printing the pthread_t does not help very much.

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

On Linux systems, you can get thread ID thus:

#include pid_t tid = gettid(); 

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

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

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?.

pid_t tid = syscall(SYS_gettid); 

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

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() .

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

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

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

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.

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"); 

Источник

Читайте также:  Docker exec it linux

How can you get the Linux thread Id of a std::thread()

I was playing with std::thread and I was wondering how is it possible to get the thread id of a new std::thread() , I am not talking about std::thread::id but rather the OS Id given to the thread ( you can view it using pstree ). This is only for my knowledge, and it’s targeted only to Linux platforms (no need to be portable). I can get the Linux Thread Id within the thread like this :

#include #include #include #include #include void SayHello() < std::cout int main (int argc, char *argv[])

But how can I retrieve the same id within the main loop ? I did not find a way using std::thread::native_handle . I believed it was possible to get it trough pid_t gettid(void); since the c++11 implementation relies on pthreads, but i must be wrong. Any advices ? Thank you.

@AndyProwl - native_handle() and native_handle_type are not required to exist, and if they do exist, what you can do with the resulting object is implementation-defined. There are no portable semantics. Maybe a particular implementation supports doing this, but that's a matter between the user and the library documentation.

@PeteBecker: I understand that, but I was assuming the OP is OK with doing something non-portable (as he is specifically targeting one platform), and I expected the implementation to provide such a basic information. I understand it is not required to provide it, but I would find it weird if it didn't.

Источник

Which Linux syscall is used to get a thread's ID?

I have to implement a wrapper function that serves as pthread_self() to get a pthread ID but I've been searching and haven´t found which syscall does this. Reading another post from Stack O. I know clone() is used to create threads, also that I can trace the syscalls with ptrace() but before tracing it by hand. could someone knows which syscall is?

4 Answers 4

There are 3 different IDs for a linux process thread: pid, pthread id, and tid.

The 'pid' is global and equivalent to the parent process id, and is easily obtained by 'getpid()'. This value is unique, but only for the duration of an the active process assigned the given id. This value may be 'recycled' for a new process after a process is terminated and new ones are spawned. This value is the same across all threads, within a process. This value is what you'll see in top, and htop, 'ps -ef', and pidstat.

The 'pthread id' is reported by pthread_create() and phtread_self(). This is value is unique only within the process, and only for the duration of the assign thread. This value may be 'recycled' as threads are terminated and spawned. This value is not unique across the system, nor across threads that have been terminated and started. This value is NOT visible outside of a program. This value is opaque and may be a pointer or structure depending on the platform.

The 'tid' Thread id is reported by gettid(). This was introduced to Linux 2.4, and does not appear to be available on other platforms. This value is unique within the process and across the system. This value is reported by top and htop, and 'pidstat -t'. I'm not 100% certain, but suspect this value can be 'recycled' as processes are terminated and spawned. This is the value that appears in the Linux tools 'top','htop', 'pidstat -t', and 'ps -efL', when shown threads.

Читайте также:  Линукс где посмотреть параметры компьютера

You can obtain 'gettid()' through:

My CentOS 6.5 is not properly setup and missing the gettid prototype, though the documentation says it should be present through the above #includes. Here is a macro that mimics 'gettid':

#ifndef gettid // equivalent to: pid_t gettid(void) #define gettid() syscall(SYS_gettid) #endif 

Be aware that since this is a syscall(), you'll gain efficiency by caching the result and avoiding repeatedly using the syscall().

Источник

Is there an async-safe way to get the current thread ID in Linux?

Is there any way to get the current thread ID from a signal handler in Linux? The getpid() method does what I want, but it is not clear if it is async-safe. man 7 signal provides a list of POSIX methods which are async safe, but this tells us nothing about non-POSIX methods such as getpid() . Presumably some of the many non-POSIX methods Linux has added are async safe, but I can't find the list. There is also this answer which claims that all direct (not multiplexed) syscalls are async safe, but provides no evidence. The goal is to build some kind of async-safe thread local storage, since __thread is not safe in the general case. It doesn't have to be the "Linux thread ID" - any consistent thread ID would be fine. For example pthread_self would be great, but there is nothing claiming that is async safe. If we examine the implementation of that method in glibc Linux, it defers to the THREAD_SELF macro, which looks like:

It seems to be that this should be async-safe, if the thread in question was created under a regime that populates the gs resgister (perhaps all threads in Linux are, I'm not sure). Still looking at that header makes me pretty scared.

That would be fine also, but there is no indication that method is async-safe, and it is not true that pthreads methods are async safe in general (certainly, the mutex methods are not). Maybe I could use the platform specific implementation of pthread_self to hack up an explicit version of the method that I know to be threadsafe?

That inline asm snippet is certainly async-safe. What evil could happen if another signal is received while this executes? None. (Note by the way that getpid is not really much of a syscall -- glibc only does a "syscall" on the first attempt and caches the value thereafter, and the "syscall" in reality goes into the vDSO).

Right, I think the inline asm is safe too, but it just happens to be a particular implementation on some platform, and doens't a guarantee that the implementation won't change in the future etc. In fact, I realize now I grabbed the 32-bit implementation - I believe it's different in x64 (more relevant to my case).

Источник

Оцените статью
Adblock
detector