From 8e591c16c2da8167254c175029c903a7d1de4605 Mon Sep 17 00:00:00 2001 From: Jan Steemann Date: Tue, 2 Aug 2016 12:25:46 +0200 Subject: [PATCH] fixed random number generator initialization --- lib/Basics/HybridLogicalClock.h | 10 +++++----- lib/Random/RandomGenerator.cpp | 21 +++++++++------------ 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/lib/Basics/HybridLogicalClock.h b/lib/Basics/HybridLogicalClock.h index 3c285e2be2..b11f93dff0 100644 --- a/lib/Basics/HybridLogicalClock.h +++ b/lib/Basics/HybridLogicalClock.h @@ -143,11 +143,7 @@ class HybridLogicalClock { } return r; } - - private: - // helper to compute the offset between epoch and 1970 - uint64_t computeOffset1970(); - + // helper to get the physical time in milliseconds since the epoch: uint64_t getPhysicalTime() { auto now = _clock.now(); @@ -158,6 +154,10 @@ class HybridLogicalClock { return ms; } + private: + // helper to compute the offset between epoch and 1970 + uint64_t computeOffset1970(); + static uint64_t extractTime(uint64_t t) { return t >> 20; } static uint64_t extractCount(uint64_t t) { return t & 0xfffffUL; } diff --git a/lib/Random/RandomGenerator.cpp b/lib/Random/RandomGenerator.cpp index 437efb5aab..6ef2ca9cc0 100644 --- a/lib/Random/RandomGenerator.cpp +++ b/lib/Random/RandomGenerator.cpp @@ -31,7 +31,9 @@ #endif #include "Basics/Exceptions.h" +#include "Basics/HybridLogicalClock.h" #include "Basics/Thread.h" +#include "Basics/hashes.h" #include "Logger/Logger.h" using namespace arangodb; @@ -42,16 +44,12 @@ using namespace arangodb::basics; // ----------------------------------------------------------------------------- unsigned long RandomDevice::seed() { - unsigned long s = (unsigned long)time(0); - - struct timeval tv; - int result = gettimeofday(&tv, 0); - - s ^= static_cast(tv.tv_sec); - s ^= static_cast(tv.tv_usec); - s ^= static_cast(result); - s ^= static_cast(Thread::currentProcessId()); + HybridLogicalClock clock; + unsigned long s = static_cast(clock.getPhysicalTime()); + TRI_pid_t pid = Thread::currentProcessId(); + s ^= static_cast(TRI_Crc32HashPointer(&pid, sizeof(TRI_pid_t))); + s = static_cast(TRI_Crc32HashPointer(&s, sizeof(unsigned long))); return s; } @@ -76,7 +74,7 @@ int32_t RandomDevice::random(int32_t left, int32_t right) { } uint32_t range = static_cast(right - left + 1); - + switch (range) { case 0x00000002: return power2(left, 0x00000002 - 1); @@ -353,8 +351,7 @@ class RandomDeviceCombined : public RandomDevice { class RandomDeviceMersenne : public RandomDevice { public: RandomDeviceMersenne() - : engine(static_cast( - std::chrono::system_clock::now().time_since_epoch().count())) {} + : engine(RandomDevice::seed()) {} uint32_t random() { return engine(); }