- 4 commands to check thread count per process (threads vs processes) in Linux
- Threads vs Processes
- Show threads per process
- 1. Using PID task
- 2. Using ps command
- 3. Using pstree command
- 4. Using top command
- Check thread count per process
- 1. Using PID status
- 2. Using ps command
- Check number of threads allowed in Linux system?
- What is the maximum processes count allowed in Linux?
- Related Posts
- Linux process and threads
- Process group
- Session (multiple process groups)
- Create a model of the daemon
- A picture to understand the thread:
- Main thread and child thread
- Create thread
- Create multiple child threads in a loop
- Single thread exit
- Recycle child thread resources
- related functions
- Thread attributes
- Thread synchronization
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.
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.
Related Posts
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!!
Источник
Linux process and threads
1. Belongs to the background service process
2. Independent of the control terminal
3. Perform a task periodically
4. Not affected by logging out of users
5. Generally use names ending in d
Process group
Leader: The first process in the group
Process group Process group leader’s ID
Session (multiple process groups)
Notes on creating a session:
1. Created when the process leader cannot
2. The process that created the session becomes the leader of the new process group
3. The created session will discard the original control terminal
4. General steps: fork(), the parent process dies, the child process creates a session
Get the ID of the session to which the process belongs:
pid_t getsid(pid_t pid);
Create a conversation:
pid_t setsid(void);
Create a model of the daemon
1. Fork the child process, the parent process exits (necessary)
2. The child process creates a new session (necessary)
setsid();
3. Change the current working directory chdir
4. Reset file mask
Increase the flexibility of sub-process program operation
umask(0);
5. Close the file descriptor
close(0)
close(1)
close(2)
release resources
6. Perform core work (necessary)
operation result:
From the output on the right, it can be seen that the a.out process has no output and has not ended. Instead, it runs in the background and discards the current control terminal. Execute at this time ps aux Command, as shown below, you can find that the a.out process is still active.
Example: Write a daemon, get the system time every 2S, and write this time to the disk file
NO.1: Create a daemon
NO.2: One timer, triggered once every 2S
setitimer
sleep
NO.3: Signal capture
operation result:
(After compiling and running process_work.c, use cd .. Command to exit the current directory, and then use ls Command to view the files in the current directory, you can find the temp.txt file, use cat temp.txt Command to open the file to see the result of the third terminal on the right)
A picture to understand the thread:
Main thread and child thread
Under Linux, threads are processes, which are lightweight processes. For the kernel, threads are processes.
The difference between multi-process and multi-thread:
Multi-process:
——-Resources that are always shared:
——Thread saves resources
Create thread
Return value: return 0 on success, error number on failure
Parameters:
thread: outgoing parameter, after the thread is created successfully, it will be set to an appropriate value
attr: pass NULL by default
start_routine: sub-thread processing function
arg: the parameter of the callback function
operation result:
Create multiple child threads in a loop
operation result:
Note:
1. Among them, the warning part can be ignored in this program, because it is caused by the mismatch of int and char types in the program, but in this program, The child threads share the same block address, so don’t worry.
2. In the program, the fourth parameter of the pthread_create function cannot pass the address, because these sub-threads share the same address space, which will cause the same thread to appear multiple times in the output result Serial number.
3. In the output, due to the competition between threads for system resources, the output sequence numbers are not sequential.
Single thread exit
void pthread_exit(void *retval);
retval must point to the global, heap
This function allows a single thread to exit without affecting other threads
operation result:
Recycle child thread resources
pthread_join-Block waiting for thread exit, get thread exit status
int pthread_join(pthread_t thread,void **retval);
Parameters:
thread: the thread id of the child thread to be recycled
retval: read the status information carried when the thread exits
—-outgoing parameters
—-void *ptr;
—-pthread_join(pthid,&ptr);
—-The pointed memory and pthread_exit parameter point to the same memory address
operation result:
related functions
Thread separation
int pthread_detach(pthread_t thread);
Note: After calling this function, there is no need to call pthread_join, and the child thread will automatically recycle its pcb
Kill/cancel thread
int pthread_cancel(pthread_t thread);
Note: A system call must be made within the processing function corresponding to the child thread to be killed. (Pthread_testcancel(), write(), read(), printf, etc. will make system calls)
Compare whether two thread IDs are equal (reserved function)
int pthread_equal(pthread_t t1,pthread_t t2);
Thread attributes
In the thread creation function pthread_create, the second parameter pthread_attr_t attr is the attribute of the thread function, and its data type is pthread_attr_t.
Thread attribute operation function: initialization of thread attribute variables:
int pthread_attr_init(pthread_attr_t* attr);
Set thread separation properties:
int pthread_attr_setdetachstate(
pthread_attr_t* attr,
int detachstate
);
parameter:
attr: thread attributes
detachstate:
PTHREAD_CREATE_DETACHED (separate)
PTHREAD_CREATE_JOINABLE (non-separable)
Release thread resource function:
int pthread_attr_destroy(pthread_attr_t* attr);
The following code is an example of setting separation properties:
operation result:
Thread synchronization
When cpu is counting:
- The register only stores a small amount of data
- Real-time data exchange with physical memory
When taking a value: - By memory address
Look at a piece of code:
operation result:
In the output result, there is such a phenomenon of overwritten data confusion. The following are the reasons for this phenomenon:
- Shared resource
- cpu scheduling problem
Solution: - Thread synchronization, that is, perform operations in order
The idea of thread synchronization:
By locking the source code of shared resources to ensure thread synchronization and the correctness of resource acquisition
Example: If thread 1 wants to access the shared resource, it needs to determine whether the shared resource is locked. If it is locked, thread 1 is blocked on this lock; if the lock is open , Thread 1 accesses the shared resource and locks it. When thread 1 accesses the shared resource, the lock is released.
Originally, multiple threads can access shared resources in parallel, and through the locking mechanism, parallel to serial is realized.
Источник