Commit ba2db8d9 authored by Yedidya Feldblum's avatar Yedidya Feldblum Committed by Facebook GitHub Bot

SingletonThreadLocal::try_get()

Summary: Accesses the per-thread singleton if it has already been created.

Reviewed By: amlannayak

Differential Revision: D31003518

fbshipit-source-id: 959418c4bc81da2b0ab7c639cdddb6d0beaf0121
parent 06e4b1aa
......@@ -132,13 +132,11 @@ class SingletonThreadLocal {
SingletonThreadLocal() = delete;
FOLLY_ALWAYS_INLINE static WrapperTL& getWrapperTL() {
(void)unique; // force the object not to be thrown out as unused
return detail::createGlobal<WrapperTL, Tag>();
}
FOLLY_NOINLINE static Wrapper& getWrapper() {
(void)unique; // force the object not to be thrown out as unused
return *getWrapperTL();
}
FOLLY_NOINLINE static Wrapper& getWrapper() { return *getWrapperTL(); }
FOLLY_NOINLINE static Wrapper& getSlow(LocalCache& cache) {
if (threadlocal_detail::StaticMetaBase::dying()) {
......@@ -158,6 +156,11 @@ class SingletonThreadLocal {
return FOLLY_LIKELY(!!cache.cache) ? *cache.cache : getSlow(cache);
}
static T* try_get() {
auto* wrapper = getWrapperTL().getIfExist();
return wrapper ? &wrapper->object : nullptr;
}
class Accessor {
private:
using Inner = typename WrapperTL::Accessor;
......
......@@ -47,6 +47,15 @@ struct Foo {
using FooSingletonTL = SingletonThreadLocal<Foo>;
} // namespace
TEST(SingletonThreadLocalTest, TryGet) {
struct Foo {};
using FooTL = SingletonThreadLocal<Foo>;
EXPECT_EQ(nullptr, FooTL::try_get());
FooTL::get();
EXPECT_NE(nullptr, FooTL::try_get());
EXPECT_EQ(&FooTL::get(), FooTL::try_get());
}
TEST(SingletonThreadLocalTest, OneSingletonPerThread) {
static constexpr std::size_t targetThreadCount{64};
std::atomic<std::size_t> completedThreadCount{0};
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment