Reputation: 73
Say I am running a simple C program. How to know which thread is executing this program? Or Is there any way so that I am sure that my program is translated into a process and this process is again divided into threads. Very sorry for any wrong understanding of the whole concept. It would be very nice if there is an example to explain the solution to my confusion (Actually I want to ask directly how to output process id--->no. of threads , and list all of the thread id's ).How to visualize the above concepts (If they are correct BTW)
Upvotes: 0
Views: 2383
Reputation: 7897
Unless otherwise stated, a program consists of exactly one thread, which is the main thread. More threads may be created by calling pthread_create (from ). You can see the exact number of threads in a program if you look at /proc/pid/status (replacing pid with the process id).
In a nutshell, think of the process as a container, for one or more threads. It is the threads themselves which execute (a thread is simply a register state), whereas the process contains the virtual memory image, open file descriptors, and other "objects".
Looking at the status file, you will see "TGID" and "PID" fields. The "PID" is actually the thread id, whereas the "TGID" is the thread group id, which is the true process id. For simple processes (those with one thread) these are equal. But for multi-threaded (2 threads or more), they will be equal only for the main thread. Anywhere but this file, "PID" really does mean the process id, as Linux imitates the UNIX standard.
Additional commands you may want to try: ps -L : this will show you the "LWP" (which is the thread identifier). You can identify multithreaded programs if you look at ps's "STATE" column containing "l" , indicating multithreaded processes.
Upvotes: 1