Linux thread and process

4 commands to check thread count per process (threads vs processes) in Linux

Table of Contents

In Linux, some processes are divided into pieces called threads. In one liner, threads are essentially just processes with a shared address space on Linux. In this article we will get some brief overview on threads and processes, also some examples to show threads per process, check thread count per process, check number of threads allowed, count threads and some more related topics.

Threads vs Processes

  • A thread is very similar to a process, it has an identifier (TID, or thread ID), and the kernel schedules and runs threads just like processes.
  • However, unlike separate processes, which usually do not share system resources such as memory and I/O connections with other processes, all threads inside a single process share their system resources and some memory.
  • A process with one thread is single-threaded , and a process with more than one thread is multithreaded .
  • All processes start out single-threaded . This starting thread is usually called the main thread. The main thread may then start new threads in order for the process to become multithreaded, similar to the way a process can call fork() to start a new process.
  • The primary advantage of a multithreaded process is that when the process has a lot to do, threads can run simultaneously on multiple processors, potentially speeding up computation.
  • Although you can also achieve simultaneous computation with multiple processes, threads start faster than processes, and it is often easier and/or more efficient for threads to intercommunicate using their shared memory than it is for processes to communicate over a channel such as a network connection or a pipe.

Show threads per process

1. Using PID task

You can count threads with the list of available sub directories inside /proc/

/task/ . The count of total available sub-directories inside this part is directly proportional to the thread count per process for the provided PID.

For example to check java thread count, I have a Java process for which you can see I have multiple sub-directories so it means this is a multi threaded process. using ls command under this path you can show threads per process for java

But then again I have another process for which as you can see I have single sub-directory hence we know this is a single thread process

2. Using ps command

You can also use » ps » command to show threads per process. With » ps » we can list LWP (Light Weight process) which depicts Thread ID of the respective process and NWLP (Number of Threads).

To show threads per process using ps command you can use below argument

3. Using pstree command

You can also use pstree to show threads per process. Here as you see java thread count and check number of threads for java process

4. Using top command

In top , by default we will not be able to see thread count per process. But when running top , it is possible to change which fields to display and add this column to print thread count per process can be added manually.

  • Press f
  • This will show a list of fields that top can display. The fields that are displayed in bold are the ones that top will display.
  • Use the down arrow to navigate to «nTH» (Number of Threads).
  • Press to select «nTH«
  • Press ‘s‘ to sort on number of threads.
  • Press ‘q‘ to display the data of threads count.
Читайте также:  Невозможно запустить установщик windows

Next you should see a new column at the end of top command with number of thread (nTH) column to show threads per process

Check thread count per process

Next you can use the above explained commands to also check thread count per process by customising them a little bit.

1. Using PID status

To check thread count per process you can use below command. For example here java thread count is 59 threads in my Linux environment

While amsHelper process has single thread

2. Using ps command

We used ps command to show threads per process and count threads, we can also use » ps » command to get LWP and NLWP details, which when combined with » wc » we can count threads per process.

To check thread count per process for a particular PID for example to check java thread count:

Check number of threads allowed in Linux system?

Linux doesn’t have a separate threads per process limit, j ust a limit on the total number of processes on the system . This value controls the maximum number of threads that can be created using fork() . During initialization the kernel sets this value such that even if the maximum number of threads is created

To check number of threads which Linux system can allow

The minimum number of threads that can be written to threads-max is 20 .
The maximum value that can be written to threads-max is given by the constant FUTEX_TID_MASK (0x3fffffff) .
If a value outside of this range is written to threads-max an error EINVAL occurs.

The default value depends on memory size. You can use threads-max to check number of threads allowed in Linux. You can increase thread count per process limit like this:

There is also a limit on the number of processes (an hence threads) that a single user may create, see ulimit for details regarding these limits:

Here, the system is able to create 35,000 threads/processes in total and a single user can create 10000 number of processes.

The logic is very simple here every CPU can execute 1 process at a time, if there are 8 cores that means 8 to 10 processes at a time can be executed easily without any stress but if number of running or runnable threads per CPU increases drastically then there will be performance issue.

What is the maximum processes count allowed in Linux?

Verify the value for kernel.pid_max

Here I can execute 35,000 processes simultaneously in my system that can run in separate memory spaces.

To change the value of kernel.pid_max to 65534:

Lastly I hope the steps from the article to show threads per process, check thread count per process, check number of threads allowed on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

What are Linux Processes, Threads, Light Weight Processes, and Process State

Linux has evolved a lot since its inception. It has become the most widely used operating system when in comes to servers and mission critical work. Though its not easy to understand Linux as a whole but there are aspects which are fundamental to Linux and worth understanding.

In this article, we will discuss about Linux processes, threads and light weight processes and understand the difference between them. Towards the end, we will also discuss various states for Linux processes.

Читайте также:  Комплект обоев для windows 10

Linux Processes

In a very basic form, Linux process can be visualized as running instance of a program. For example, just open a text editor on your Linux box and a text editor process will be born.

Here is an example when I opened gedit on my machine :

First command (gedit &) opens gedit window while second ps command (ps -aef | grep gedit) checks if there is an associated process. In the result you can see that there is a process associated with gedit.

Processes are fundamental to Linux as each and every work done by the OS is done in terms of and by the processes. Just think of anything and you will see that it is a process. This is because any work that is intended to be done requires system resources ( that are provided by kernel) and it is a process that is viewed by kernel as an entity to which it can provide system resources.

Processes have priority based on which kernel context switches them. A process can be pre-empted if a process with higher priority is ready to be executed.

For example, if a process is waiting for a system resource like some text from text file kept on disk then kernel can schedule a higher priority process and get back to the waiting process when data is available. This keeps the ball rolling for an operating system as a whole and gives user a feeling that tasks are being run in parallel.

Processes can talk to other processes using Inter process communication methods and can share data using techniques like shared memory.

In Linux, fork() is used to create new processes. These new processes are called as child processes and each child process initially shares all the segments like text, stack, heap etc until child tries to make any change to stack or heap. In case of any change, a separate copy of stack and heap segments are prepared for child so that changes remain child specific. The text segment is read-only so both parent and child share the same text segment. C fork function article explains more about fork().

Linux Threads vs Light Weight Processes

Threads in Linux are nothing but a flow of execution of the process. A process containing multiple execution flows is known as multi-threaded process.

For a non multi-threaded process there is only execution flow that is the main execution flow and hence it is also known as single threaded process. For Linux kernel , there is no concept of thread. Each thread is viewed by kernel as a separate process but these processes are somewhat different from other normal processes. I will explain the difference in following paragraphs.

Threads are often mixed with the term Light Weight Processes or LWPs. The reason dates back to those times when Linux supported threads at user level only. This means that even a multi-threaded application was viewed by kernel as a single process only. This posed big challenges for the library that managed these user level threads because it had to take care of cases that a thread execution did not hinder if any other thread issued a blocking call.

Later on the implementation changed and processes were attached to each thread so that kernel can take care of them. But, as discussed earlier, Linux kernel does not see them as threads, each thread is viewed as a process inside kernel. These processes are known as light weight processes.

The main difference between a light weight process (LWP) and a normal process is that LWPs share same address space and other resources like open files etc. As some resources are shared so these processes are considered to be light weight as compared to other normal processes and hence the name light weight processes.

Читайте также:  Расширение virtualbox для linux

So, effectively we can say that threads and light weight processes are same. It’s just that thread is a term that is used at user level while light weight process is a term used at kernel level.

From implementation point of view, threads are created using functions exposed by POSIX compliant pthread library in Linux. Internally, the clone() function is used to create a normal as well as alight weight process. This means that to create a normal process fork() is used that further calls clone() with appropriate arguments while to create a thread or LWP, a function from pthread library calls clone() with relevant flags. So, the main difference is generated by using different flags that can be passed to clone() function.

Read more about fork() and clone() on their respective man pages.

Linux Process States

Life cycle of a normal Linux process seems pretty much like real life. Processes are born, share resources with parents for sometime, get their own copy of resources when they are ready to make changes, go through various states depending upon their priority and then finally die. In this section will will discuss various states of Linux processes :

  • RUNNING – This state specifies that the process is either in execution or waiting to get executed.
  • INTERRUPTIBLE – This state specifies that the process is waiting to get interrupted as it is in sleep mode and waiting for some action to happen that can wake this process up. The action can be a hardware interrupt, signal etc.
  • UN-INTERRUPTIBLE – It is just like the INTERRUPTIBLE state, the only difference being that a process in this state cannot be waken up by delivering a signal.
  • STOPPED – This state specifies that the process has been stopped. This may happen if a signal like SIGSTOP, SIGTTIN etc is delivered to the process.
  • TRACED – This state specifies that the process is being debugged. Whenever the process is stopped by debugger (to help user debug the code) the process enters this state.
  • ZOMBIE – This state specifies that the process is terminated but still hanging around in kernel process table because the parent of this process has still not fetched the termination status of this process. Parent uses wait() family of functions to fetch the termination status.
  • DEAD – This state specifies that the process is terminated and entry is removed from process table. This state is achieved when the parent successfully fetches the termination status as explained in ZOMBIE state.

Источник

How Linux handles threads and process scheduling

I’m trying to understand how Linux handles process scheduling and thread scheduling. I read that Linux can schedule both processes and threads.

Does Linux have a thread scheduler AND a process scheduler? If yes, how do they cooperate?

3 Answers 3

The Linux kernel scheduler is actually scheduling tasks, and these are either threads or (single-threaded) processes.

So a task (a task_struct inside the kernel), in the context of the scheduler, is the thing being scheduled, and can be some kernel thread like kworker or kswapd , some user thread of a multi-threaded process (like firefox ), or the single-thread of a single-threaded process (like bash ), identified with that single-threaded process.

A process is a non-empty finite set (sometimes a singleton) of threads sharing the same virtual address space (and other things like file descriptors, working directory, etc etc. ). See also credentials(7), capabilities(7) etc.

Threads on Linux are kernel threads (in the sense of being managed by the kernel, which also creates its own threads), created by the Linux specific clone syscall (which can also be used to create processes on Linux). The pthread_create function is probably built (on Linux) above clone inside NPTL and Gnu Libc (which integrated NPTL on Linux) and musl-libc.

Источник

Оцените статью