linux的pthread_self与gettid的返回值和开销的区别
linux的pthread_self与gettid的返回值和开销的区别
pthread_self()是POSIX的实现,它的返回值是pthread_t,pthread_t在linux中实际是无符号长整型,即unsigned long。
gettid是系统调用,它的返回值是pid_t,在linux上是一个无符号整型。
测试机为Intel i7 860 2.8GHz,八核,各调用一千万次,二者效率基本一致,测试代码如下:
#include<stdio.h> #include <sys/syscall.h> #include <unistd.h> #include <pthread.h> pid_t gettid(void){ return syscall(SYS_gettid); } int main() { int i=0; printf("%u %lu",gettid(),pthread_self()); for(i=0;i<10000000;i++) { gettid(); // pthread_self(); } }
gettid()测试结果
[root@test]# time ./a.out real 0m0.572s user 0m0.230s sys 0m0.342s
pthread_self()测试结果
[root@test]# time ./a.out real 0m0.570s user 0m0.250s sys 0m0.321s