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.