【发布时间】:2013-11-01 11:18:07
【问题描述】:
我们正在使用 boost 线程特定指针来仅为该特定线程存储一些全局数据。下面是当有人调用 GetInstance() 时我们返回的单例。
我的问题是,与普通指针访问相比,获取线程特定指针 (m_tspConnectionManager.get();) 大约需要多长时间?
我使用了下面的代码(我调用了 .get() 方法两次),完成整个函数大约需要 3 秒。
typedef boost::thread_specific_ptr<ConnectionManager> ConnMgrPtr;
static ConnMgrPtr m_tspConnectionManager;
static ConnectionManager* GetInstance()
{
if(!m_tspConnectionManager.get())
{
//first time called by this thread
//ConnectionManager* to be used in all subsequent calls from this thread
m_tspConnectionManager.reset(new ConnectionManager());
}
return m_tspConnectionManager.get();
}
现在,我将上面的代码更改为只调用一次 .get() 方法,大约需要 1.9 秒。
static ConnectionManager* GetInstance()
{
ConnectionManager* pConnMgr = m_tspConnectionManager.get();
if(pConnMgr == NULL)
{
//first time called by this thread
//ConnectionManager* to be used in all subsequent calls from this thread
m_tspConnectionManager.reset(new ConnectionManager());
}
return pConnMgr != NULL ? pConnMgr : m_tspConnectionManager.get();
}
所以,只要不调用 .get() 方法,我就可以看到 1.1 秒的性能提升。我一直在试图了解我们如何获得收益? 注意:这个收益可能是多次调用 GetInstance() 函数的集体收益。只是想了解这里的单个呼叫增益。
【问题讨论】:
-
thread_specific_ptr::get() 绝对不可能花费 1.1 秒来执行。即使在调试模式下。你是如何安排这些事情的?
-
对不起,我没有正确澄清,但 1.1 秒是集体收益,即多次调用函数。我只是想了解大概的单次通话增益。
标签: c++ windows multithreading performance thread-local-storage