Use thread-local in RequestContext::getStaticContext
authorYedidya Feldblum <yfeldblum@fb.com>
Tue, 16 Jan 2018 17:32:21 +0000 (09:32 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Tue, 16 Jan 2018 17:37:12 +0000 (09:37 -0800)
Summary:
[Folly] Use thread-local in `RequestContext::getStaticContext`.

`folly::SingletonThreadLocal` uses `folly::ThreadLocal`. However, `static FOLLY_TLS` (`static __thread`) is always faster than `folly::ThreadLocal` for thread-local singletons for which iteration is not required.

Reviewed By: djwatson

Differential Revision: D6725091

fbshipit-source-id: 9979f39677284b1051cb109b461097495d77ca17

folly/io/async/Request.cpp

index f8cca8b..644c208 100644 (file)
@@ -141,10 +141,16 @@ std::shared_ptr<RequestContext> RequestContext::setContext(
 }
 
 std::shared_ptr<RequestContext>& RequestContext::getStaticContext() {
-  using SingletonT = SingletonThreadLocal<std::shared_ptr<RequestContext>>;
-  static SingletonT singleton;
-
+  using T = std::shared_ptr<RequestContext>;
+#ifdef FOLLY_TLS
+  alignas(alignof(T)) static FOLLY_TLS unsigned char storage[sizeof(T)];
+  static FOLLY_TLS T* singleton;
+  return singleton ? *singleton : *(singleton = new (storage) T());
+#else
+  struct PrivateTag {};
+  static SingletonThreadLocal<T, PrivateTag> singleton;
   return singleton.get();
+#endif
 }
 
 RequestContext* RequestContext::get() {