Commit 895c8a62 authored by Andrii Grynenko's avatar Andrii Grynenko Committed by Facebook Github Bot

Use SingletonThreadLocal in folly::Random

Summary: folly::SingletonThreadLocal should be used for all thread-local singletons to avoid SDOF.

Reviewed By: yfeldblum

Differential Revision: D4253009

fbshipit-source-id: 5b4ca57a7a77b7b54c94630a2a29d13b84a3af27
parent 4dd1dd68
...@@ -21,13 +21,14 @@ ...@@ -21,13 +21,14 @@
#include <random> #include <random>
#include <array> #include <array>
#include <glog/logging.h>
#include <folly/CallOnce.h> #include <folly/CallOnce.h>
#include <folly/File.h> #include <folly/File.h>
#include <folly/FileUtil.h> #include <folly/FileUtil.h>
#include <folly/SingletonThreadLocal.h>
#include <folly/ThreadLocal.h> #include <folly/ThreadLocal.h>
#include <folly/portability/SysTime.h> #include <folly/portability/SysTime.h>
#include <folly/portability/Unistd.h> #include <folly/portability/Unistd.h>
#include <glog/logging.h>
#ifdef _MSC_VER #ifdef _MSC_VER
# include <wincrypt.h> # include <wincrypt.h>
...@@ -123,28 +124,30 @@ void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) { ...@@ -123,28 +124,30 @@ void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
ptr_ += size; ptr_ += size;
} }
struct RandomTag {};
} // namespace } // namespace
void Random::secureRandom(void* data, size_t size) { void Random::secureRandom(void* data, size_t size) {
static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice; static SingletonThreadLocal<BufferedRandomDevice, RandomTag>
bufferedRandomDevice->get(data, size); bufferedRandomDevice;
bufferedRandomDevice.get().get(data, size);
} }
class ThreadLocalPRNG::LocalInstancePRNG { class ThreadLocalPRNG::LocalInstancePRNG {
public: public:
LocalInstancePRNG() : rng(Random::create()) { } LocalInstancePRNG() : rng(Random::create()) {}
Random::DefaultGenerator rng; Random::DefaultGenerator rng;
}; };
ThreadLocalPRNG::ThreadLocalPRNG() { ThreadLocalPRNG::ThreadLocalPRNG() {
static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance; static SingletonThreadLocal<ThreadLocalPRNG::LocalInstancePRNG, RandomTag>
local_ = localInstance.get(); localInstancePRNG;
local_ = &localInstancePRNG.get();
} }
uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) { uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) {
return local->rng(); return local->rng();
} }
} }
...@@ -65,9 +65,9 @@ class ThreadLocalPRNG { ...@@ -65,9 +65,9 @@ class ThreadLocalPRNG {
ThreadLocalPRNG(); ThreadLocalPRNG();
private:
class LocalInstancePRNG; class LocalInstancePRNG;
private:
static result_type getImpl(LocalInstancePRNG* local); static result_type getImpl(LocalInstancePRNG* local);
LocalInstancePRNG* local_; LocalInstancePRNG* local_;
}; };
......
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