Getting started with Linux: count the number of threads of a process in Linux
Problem: I am running a program, which will derive multiple threads at runtime. I want to know how many threads the program will have at runtime. In Linux, what is the simplest way to check the number of threads of a process?
If you want to see the number of threads for each process in Linux, you can do this using the following methods.
Method 1:/proc
The proc pseudo File System resides in the/proc directory. This is the easiest way to view the number of threads of any active process. The/proc directory is output in the form of readable text files, providing information related to existing processes and system hardware, such as CPU, interrupt, memory, and disk.
$ cat/proc/<pid>/status
The preceding command displays the Process <pid> details, including the Process status (for example, sleeping, running), parent process PID, UID, GID, and the number of file descriptors used, and the number of context switches. The output also includes the total number of threads created by the process.
Threads:<N>
For example, check the number of threads of the PID 20571 process:
$ cat/proc/20571/status
The output indicates that the process has 28 threads.
Alternatively, you can simply count the number of subdirectories in/proc // task, as shown below.
$ ls/proc/<pid>/task |wc
This is because, for each thread created in a process/proc/<pid>/taskCreate a directory named as its thread ID. Therefore/proc/<pid>/taskThe total number of threads in the process.
Method 2: ps
If you are a loyal user of powerful ps commands, this command can also tell you the number of threads of a process (using the "H" option. The following command outputs the number of threads of the process. The "h" option must be prefixed.
$ ps hH p <pid>|wc-l
If you want to monitor the hardware resources (CPU & memory) consumed by different threads of a process, refer to this tutorial.
Via: http://ask.xmodulo.com/number-of-threads-process-linux.html
Author: Dan Nanni Translator: strugglingyouth Proofreader: wxy
This article was originally translated by LCTT and launched with the Linux honor in China
This article permanently updates the link address: