Reputation: 2798
Is pthread_self()
expensive on ubuntu 12.04
?
Does it uses a system call?
I want to call pthread_self()
each time a thread wrote to log, so I'll know which thread wrote to log and mention it on the log. All threads write to the same log file.
Upvotes: 1
Views: 2686
Reputation: 2798
As dvnrrs suggested, I wrote the following code
:
#include <pthread.h>
int main(void) {
int i;
for (i = 0; i < 100000; i++) {
pthread_self();
}
}
And ran it with time code
and got:
real 0m0.001s
user 0m0.000s
sys 0m0.001s
Running the loop for 10000000 times gave me:
real 0m0.045s
user 0m0.044s
sys 0m0.000s
I ran it with strace -c -ttT ./code
and got
% time seconds usecs/call calls errors syscall
-nan 0.000000 0 2 read
-nan 0.000000 0 3 open
-nan 0.000000 0 3 close
-nan 0.000000 0 3 fstat
-nan 0.000000 0 11 mmap
-nan 0.000000 0 5 mprotect
-nan 0.000000 0 1 munmap
-nan 0.000000 0 1 brk
-nan 0.000000 0 2 rt_sigaction
-nan 0.000000 0 1 rt_sigprocmask
-nan 0.000000 0 1 1 access
-nan 0.000000 0 1 execve
-nan 0.000000 0 1 getrlimit
-nan 0.000000 0 1 arch_prctl
-nan 0.000000 0 2 1 futex
-nan 0.000000 0 1 set_tid_address
-nan 0.000000 0 1 set_robust_list
100.00 0.000000 40 2 total
Upvotes: 4
Reputation: 5416
You can check the source code here: https://fossies.org/dox/glibc-2.19/pthread__self_8c_source.html
As you can see from the link above, pthread_self() returns THREAD_SELF, which is defined as a simple assembly movl
instruction. No system calls there. Of course, this is implementation defined. The link above refers to glibc library.
Upvotes: 5
Reputation: 40625
Even if pthread_self()
results in a syscall, it will be a relatively cheap one since it will simply look up the result. It will definitely not grab any locks (because the value you need is constant), or do anything else which is a huge performance burner. I expect something below one microsecond, but I may be wrong.
If you call it right after a write()
call, you shouldn't need to worry about the performance of pthread_self()
, because the time required for the write()
will be much longer. After all, write()
does need to grab locks to ensure POSIX semantics (i. e. that the written data becomes visible to all other processes immediately).
If your experiments show you that pthread_self()
indeed performs a syscall, you can easily cache its return value in a thread_local
global variable which you set right at the start of the pthread (the thread_local
keyword is part of the C/C++11 standards if I'm not much mistaken).
Upvotes: 0