Threads are a popular programming abstraction for parallel execution on modern operating systems. When threads are forked inside a program for multiple flows of execution, these threads share certain resources (e.g., memory address space, open files) among themselves to minimize forking overhead and avoid expensive IPC (inter-process communication) channel. These properties make threads an efficient mechanism for concurrent execution.
In Linux, threads (also called Lightweight Processes (LWP)) created within a program will have the same "thread group ID" as the program's PID. Each thread will then have its own thread ID (TID). To the Linux kernel's scheduler, threads are nothing more than standard processes which happen to share certain resources. Classic command-line tools such as ps or top, which display process-level information by default, can be instructed to display thread-level information.
Here are several ways to show threads for a process on Linux:
Using the ps command
The "-T" option for the ps command enables thread views. The following command list all threads created by a process with
For example to list the threads for the following java process:
# ps -T -p <pid>
Run the following command:
# ps -ef | grep 97947
deploy 97947 97942 1 00:51 ? 00:13:51 java
The "SID" column represents thread IDs, and "CMD" column shows thread names.
# ps -T -p 97947
PID SPID TTY TIME CMD
97947 97947 ? 00:00:00 java
97947 97948 ? 00:00:00 java
97947 97949 ? 00:00:00 java
Using the top command
The top command can show a real-time view of individual threads. To enable thread views in the top output, invoke top with "-H" option. This will list all Linux threads. You can also toggle on or off thread view mode while top is running, by pressing 'H' key.
Note how in the example above the number of threads on the system is listed.
top - 14:43:25 up 6 days, 5:40, 2 users, load average: 0.87, 0.33, 0.22
Threads: 684 total, 1 running, 683 sleeping, 0 stopped, 0 zombie
%Cpu(s): 6.3 us, 4.0 sy, 0.0 ni, 89.6 id, 0.1 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 7910136 total, 384812 free, 1603096 used, 5922228 buff/cache
KiB Swap: 8388604 total, 8239100 free, 149504 used. 5514264 avail Mem
To restrict the top output to a particular process and check all threads running inside the process:
Using htop
# top -H -p <pid>
A more user-friendly way to view threads per process is via htop, an ncurses-based interactive process viewer. This program allows you to monitor individual threads in tree views.
To enable thread views in htop, launch htop, and press F2 to enter htop setup menu. Choose "Display option" under "Setup" column, and toggle on "Tree view" and "Show custom thread names" options. Presss F10 to exit the setup.
If you found this useful, here's more on the same topic(s) in our blog:
Interested in learning more?