How to view threads of a process on Linux

Last updated on October 28, 2020 by Dan Nanni

Question: My program creates and executes multiple threads in it. How can I monitor individual threads of the program once they are created? I would like to see the details (e.g., CPU/memory usage) of individual threads with their names.

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. If you want to simply count the number of threads in a thread, check out this post instead.

Method One: ps

In ps command, -T option enables thread views. The following command list all threads created by a process with <pid>.

$ ps -T -p <pid>

The SID column represents thread IDs, and CMD column shows thread names.

Method Two: top

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.

$ top -H

To restrict the top output to a particular process <pid> and check all threads running inside the process:

$ top -H -p <pid>

Method Three: htop

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 Three view and Show custom thread names options. Presss <F10> to exit the setup.

Now you will see the follow threaded view of individual processes.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean