I would like to monitor the number of threads used by a specific process on Linux. Is there an easy way to get this information without impacting the performance of the process?
18 Answers
To get the number of threads for a given pid:
$ ps -o nlwp <pid>
Where nlwp
stands for Number of Light Weight Processes (threads). Thus ps
aliases nlwp
to thcount
, which means that
$ ps -o thcount <pid>
does also work.
If you want to monitor the thread count, simply use watch
:
$ watch ps -o thcount <pid>
To get the sum of all threads running in the system:
$ ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END { print num_threads }'
The easiest way is using "htop". You can install "htop" (a fancier version of top) which will show you all your cores, process and memory usage.
Press "Shift+H" to show all process or press again to hide it. Press "F4" key to search your process name.
Installing on Ubuntu or Debian:
sudo apt-get install htop
Installing on Redhat or CentOS:
yum install htop
dnf install htop [On Fedora 22+ releases]
If you want to compile "htop" from source code, you will find it here.
If you're looking for thread count for multiple processes, the other answers won't work well for you, since you won't see the process names or PIDs, which makes them rather useless. Use this instead:
ps -o pid,nlwp,args -p <pid_1> <pid_2> ... <pid_N>
In order to watch the changes live, just add watch
:
watch ps -o pid,nlwp,args -p <pid_1> <pid_2> ... <pid_N>
If you're interested in those threads which are really active -- as in doing something (not blocked, not timed_waiting, not reporting "thread running" but really waiting for a stream to give data) as opposed to sitting around idle but live -- then you might be interested in jstack-active.
This simple bash script runs jstack
then filters out all the threads which by heuristics seem to be idling, showing you stack traces for those threads which are actually consuming CPU cycles.