Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ thread/process identifier

Is there a portable way of getting thread and/or process identifier (string, int, ...) with C++?

like image 661
rik Avatar asked Oct 06 '08 16:10

rik


People also ask

How do I find the process thread ID?

In the GNU C Library implementation running on Linux, the process ID is the thread group ID of all threads in the process. You can get the process ID of a process by calling getpid .

What is a thread identifier?

Thread Id is a long positive integer that is created when the thread was created. During the entire lifecycle of a thread, the thread ID is unique and remains unchanged. It can be reused when the thread is terminated.

What is thread ID in C?

pthread_self() in CThe pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.

Does a thread have a process ID?

In Linux, each thread has a pid, and that's what htop shows. The “process” to which all the threads belong is the thread whose pid matches its thread group id. In your case, grep Tgid /proc/1021/status would show the value 1019 (and this would be true for all the rg identifiers shown by htop ).


1 Answers

You have a few ways, but all imply the use of an external library abstracting the thread for you.

Among the popular choices, two are:

  1. The Boost.Thread library. This is the most portable but imply working with Boost, which is a HUGE library
  2. The Qt library. This is less portable and imply to work with Qt, a big library.

If you already use any on these two libraries, I would recommend sticking with it. Otherwise, look at what other tools they provide and make a choice.

like image 145
PierreBdR Avatar answered Sep 30 '22 18:09

PierreBdR