Getting thread id in linux

Obtaining the thread ID for Java threads in Linux

I have a Java application where some threads are created (via new Thread() ). Using ps I can see they have different thread IDs (LWP column) and I would like to obtain those IDs from within the Java application. In most of the posts related to this topic that I have found (e.g., this one), the solution is to use ManagementFactory.getRuntimeMXBean().getName() . Using that method, however, gives me the PID of the main thread (even if I call it from one of the threads), so it is not really solving my problem. Is there any way to obtain the thread ID for every single Thread created by an application? Would it be possible to use JNI to accomplish it? If somehow I could interface to a C function where I could call syscall(__NR_gettid) , that could solve my problem. I really do not care about portability, so I am totally okay with a solution that would only work for a Linux machine. UPDATE: I have actually solved my problem by using JNI. Details are explained in my answer. Thank you all for your suggestions/comments.

@nhahtdh I am not 100% sure how Java threads map to Linux threads, but at least in my system, they have a given thread ID as a pthread would have. As I said, I am not really looking for a portable solution.

@betabandido: So, have you tried to implement that JNI function? Or are we supposed to do that for you?

@NiklasB. I was not asking for that. Since I am not really used to write Java code anymore, and I have never touched JNI, I just wanted to know if it is a viable option. If the answer is yes, I will definitely look at it myself.

Источник

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.

Читайте также:  Astra linux менеджер приложений

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

Источник

POSIX : How to get thread Id of a pthread in Linux | pthread_self() | pthread_equals()

In this article we will discuss how to get thread id of a pthread and compare different thread ids.

How to get thread id of current thread

Use pthread_self() to get the current thread id i.e.

#include pthread_t pthread_self(void);

It returns the thread id as pthread_t object for the calling thread. As main function is also a thread, so we can also call pthread_self() form main function too. pthread_self() never fails and always returns the thread id.

Frequently Asked:

// Get thread Id of calling thread pthread_t thId = pthread_self();

How to get thread id while creating thread

When we create a thread using pthread_create(), we pass the pointer of pthread_t as first argument. When thread is created it is set to thread id i.e.

// Thread id pthread_t threadId; // Create a thread that will call function threadFunc() as thread function. Also // pass the pointer to thread id object. This API will set the thread id in this passed argument. int err = pthread_create(&threadId, NULL, &threadFunc, NULL);

Comparing 2 thread id (pthread_t) using pthread_equal

As pthread_t can be a structure, therefore we should not compare using == operator. POSIX provides a function pthread_equal() to compare 2 pthread_t i.e.

#include int pthread_equal(pthread_t t1, pthread_t t2);
//Compare Main thread Id and newly created thread id bool result = pthread_equal(mainThreadId, threadId);

It returns 0 in case of failure and 1 in case they are equal.

Читайте также:  Файлы линукс my conf

Checkout complete example as follows,

#include #include #include #include #include #include void * threadFunc(void * arg) < // Get thread Id of calling thread pthread_t thId = pthread_self(); std::cout int main() < // Getting thread id of main function pthread_t mainThreadId = pthread_self(); std::cout else std::cout std::cout

Thread Id from Main function thread : 139687770216256 Thread Created with ID : 139687753377536 Both Main & new thread has different thread ids Waiting for thread 139687753377536 to exit Thread Id from thread function : 139687753377536 Exiting Main

To compile the above code use following command,

g++ example.cpp -lpthread

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

Читайте также:  Use linux if available

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

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