Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSIX API call to list all the pthreads running in a process

I have a multi-threaded application in a POSIX/Linux environment - I have no control over the code that creates the pthreads. At some point the process - owner of the pthreads - receives a signal.

The handler of that signal should abort,cancel or stop all the pthreads and log how many pthreads where running.

My problem is that I could not find how to list all the pthreads running in process.

like image 985
Manuel Salvadores Avatar asked Aug 13 '10 09:08

Manuel Salvadores


People also ask

Which of the following API is used for Posix thread creation?

Thread functions in C/C++ In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow.

Which statement is used to print the thread ID inside the thread routine?

The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads.

Where is Pthread library in Linux?

The pthreads run time library usually lives in /lib, while the development library usually lives in /usr/lib.

Is pthreads an API?

POSIX thread (pthread) libraries. The POSIX thread libraries are a standards based thread API for C/C++. It allows one to spawn a new concurrent process flow.


1 Answers

There doesn't seem to be any portable way to enumerate the threads in a process.

Linux has pthread_kill_other_threads_np, which looks like a leftover from the original purely-userland pthreads implementation that may or may not work as documented today. It doesn't tell you how many threads there were.

You can get a lot of information about your process by looking in /proc/self (or, for other processes, /proc/123). Although many unices have a file or directory with that name, the layout is completely different, so any code using /proc will be Linux-specific. The documentation of /proc is in Documentation/filesystems/proc.txt in the kernel source. In particular, /proc/self/task has a subdirectory for each thread. The name of the subdirectory is the LWP id; unfortunately, [1][2][3] there doesn't seem to be a way to associate LWP ids with pthread ids (but you can get your own thread id with gettid(2) if you work for it). Of course, reading /proc/self/task is not atomic; the number of threads is available atomically through /proc/self/status (but of course it might change before you act on it).

If you can't achieve what you want with the limited support you get from Linux pthreads, another tactic is to play dynamic linking tricks to provide your own version of pthread_create that logs to a data structure you can inspect afterwards.

like image 102
Gilles 'SO- stop being evil' Avatar answered Oct 08 '22 01:10

Gilles 'SO- stop being evil'