之前的一篇文章 线程私有数据 是依赖于 pthread 库实现的,而今天介绍的这个则是 gcc 提供的标识符:__thread,它只能用于修饰 POD 类型,不能修饰复合类型,如struct, class。否则会出现编译错误如:
代码参考 muduo 库里的一个参数:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <thread>
#include <sys/syscall.h>
namespace CurrentThread
{
__thread int tCachedTid = 0;
void cacheTid()
{
if(tCachedTid == 0)
{
printf("first time get tid\n");
tCachedTid = (int)syscall(SYS_gettid);
}
}
inline int tid()
{
if(tCachedTid == 0)
{
cacheTid();
}
return tCachedTid;
}
}
class CThreadProc
{
public:
CThreadProc()
{
}
~CThreadProc()
{
}
void operator()()
{
int count = 0;
while (1)
{
printf("child thread id(%lu)\n", CurrentThread::tid());
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if(count++ == 100)
{
break;
}
}
}
};
int main()
{
CThreadProc threacProc;
std::thread t(threacProc);
CThreadProc threacProc2;
std::thread t2(threacProc2);
t.join();
t2.join();
return 0;
}
变量 tCachedTid 是缓存了调用线程的线程id,当有线程调用 CurrentThread::tid() 时,第一次会调用系统调用,然后线程id缓存在了 tCachedTid,此线程再调用 CurrentThread::tid() 时,即从缓存数据里直接取,避免每次都调用系统调用,提高效率。