From a65e66ab5e853b81df182be9c4aa98b36f6b9f37 Mon Sep 17 00:00:00 2001 From: Dan Melnic <dmm@fb.com> Date: Wed, 27 Jun 2018 15:11:30 -0700 Subject: [PATCH] Make the pthread key a singleton Summary: Make the pthread key a singleton Reviewed By: yfeldblum Differential Revision: D8663589 fbshipit-source-id: 1e0c328104bd8c3d3c689dc4955a185336e74276 --- folly/detail/ThreadLocalDetail.cpp | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/folly/detail/ThreadLocalDetail.cpp b/folly/detail/ThreadLocalDetail.cpp index c8b6d9a89..31cfa4ed8 100644 --- a/folly/detail/ThreadLocalDetail.cpp +++ b/folly/detail/ThreadLocalDetail.cpp @@ -76,20 +76,30 @@ ThreadEntryList* StaticMetaBase::getThreadEntryList() { static FOLLY_TLS ThreadEntryList threadEntryListSingleton; return &threadEntryListSingleton; #else - static pthread_key_t pthreadKey; - static folly::once_flag onceFlag; - folly::call_once(onceFlag, [&]() { - int ret = pthread_key_create(&pthreadKey, nullptr); - checkPosixError(ret, "pthread_key_create failed"); - PthreadKeyUnregister::registerKey(pthreadKey); - }); + class PthreadKey { + public: + PthreadKey() { + int ret = pthread_key_create(&pthreadKey_, nullptr); + checkPosixError(ret, "pthread_key_create failed"); + PthreadKeyUnregister::registerKey(pthreadKey_); + } + + FOLLY_ALWAYS_INLINE pthread_key_t get() const { + return pthreadKey_; + } + + private: + pthread_key_t pthreadKey_; + }; + + static auto instance = detail::createGlobal<PthreadKey, void>(); ThreadEntryList* threadEntryList = - static_cast<ThreadEntryList*>(pthread_getspecific(pthreadKey)); + static_cast<ThreadEntryList*>(pthread_getspecific(instance->get())); if (UNLIKELY(!threadEntryList)) { threadEntryList = new ThreadEntryList(); - int ret = pthread_setspecific(pthreadKey, threadEntryList); + int ret = pthread_setspecific(instance->get(), threadEntryList); checkPosixError(ret, "pthread_setspecific failed"); } -- 2.26.2