random.cc 995 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. #include "util/random.h"
  7. #include <stdint.h>
  8. #include <string.h>
  9. #include <thread>
  10. #include <utility>
  11. #include "port/likely.h"
  12. #include "util/thread_local.h"
  13. #ifdef ROCKSDB_SUPPORT_THREAD_LOCAL
  14. #define STORAGE_DECL static __thread
  15. #else
  16. #define STORAGE_DECL static
  17. #endif
  18. namespace ROCKSDB_NAMESPACE {
  19. Random* Random::GetTLSInstance() {
  20. STORAGE_DECL Random* tls_instance;
  21. STORAGE_DECL std::aligned_storage<sizeof(Random)>::type tls_instance_bytes;
  22. auto rv = tls_instance;
  23. if (UNLIKELY(rv == nullptr)) {
  24. size_t seed = std::hash<std::thread::id>()(std::this_thread::get_id());
  25. rv = new (&tls_instance_bytes) Random((uint32_t)seed);
  26. tls_instance = rv;
  27. }
  28. return rv;
  29. }
  30. } // namespace ROCKSDB_NAMESPACE