1 //  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 //
6 
7 #include "util/random.h"
8 
9 #include <stdint.h>
10 #include <string.h>
11 #include <thread>
12 #include <utility>
13 
14 #include "port/likely.h"
15 #include "util/thread_local.h"
16 
17 #ifdef ROCKSDB_SUPPORT_THREAD_LOCAL
18 #define STORAGE_DECL static __thread
19 #else
20 #define STORAGE_DECL static
21 #endif
22 
23 namespace ROCKSDB_NAMESPACE {
24 
GetTLSInstance()25 Random* Random::GetTLSInstance() {
26   STORAGE_DECL Random* tls_instance;
27   STORAGE_DECL std::aligned_storage<sizeof(Random)>::type tls_instance_bytes;
28 
29   auto rv = tls_instance;
30   if (UNLIKELY(rv == nullptr)) {
31     size_t seed = std::hash<std::thread::id>()(std::this_thread::get_id());
32     rv = new (&tls_instance_bytes) Random((uint32_t)seed);
33     tls_instance = rv;
34   }
35   return rv;
36 }
37 
38 }  // namespace ROCKSDB_NAMESPACE
39