LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Command for thread (https://www.linuxquestions.org/questions/programming-9/command-for-thread-4175413772/)

utkarshrawat 06-27-2012 11:30 PM

Command for thread
 
Hi
I have a C program that consist of 5 to 6 threads ,is there any command where I can see which thread has run the most.

Nominal Animal 06-28-2012 12:06 AM

clock_gettime(CLOCK_THREAD_CPUTIME_ID, &timespec) reports the CPU time the current thread has used. For example, you could set up a (process-wide) signal handler (say for SIGRTMIN+1). The handler would call pthread_self() , locate the matching thread identifier in an array, then call clock_gettime() with the corresponding timespec entry in the array, to update the CPU time used by the thread. Any thread in the process can then use pthread_kill() to make each thread transparently update the CPU time they've used. (Other processing in that thread will not be affected, except that blocking syscalls may return EINTR. But you should always handle that correctly anyway, since it may happen whenever a signal is delivered anyway. And a lot of libraries use signals internally, so EINTR just do happen.)

Another approach is to read /proc/PID/task/TID/stat. The twelfth field after the close parenthesis tells the time spent by the thread in userspace, and the thirteenth the time spent by the thread in kernel, in system ticks (sysconf(_SC_CLK_TCK) ticks per second). I recommend reading the first line, then removing everything up to and including the final ), and then parsing the fields using sscanf(). Any other process belonging to the same user can do this.

Note that TID is a value returned by a gettid() call, and are not related to pthread_t values. You either need to have the threads report their gettid() and pthread_self() somehow, or you cannot really say which thread is which from outside the process.


All times are GMT -5. The time now is 11:52 PM.