You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
821B

  1. #include <atomic>
  2. #include <time.h>
  3. #include <sys/time.h>
  4. #include <random.hpp>
  5. #include <math.hpp>
  6. namespace rack {
  7. namespace random {
  8. thread_local Xoroshiro128Plus rng;
  9. static std::atomic<uint64_t> threadCounter {0};
  10. void init() {
  11. // Don't reset state if already seeded
  12. if (rng.isSeeded())
  13. return;
  14. // Get epoch time in microseconds for seed
  15. struct timeval tv;
  16. gettimeofday(&tv, NULL);
  17. uint64_t usec = uint64_t(tv.tv_sec) * 1000 * 1000 + tv.tv_usec;
  18. // Add number of initialized threads so far to random seed, so two threads don't get the same seed if initialized at the same time.
  19. rng.seed(usec, threadCounter++);
  20. // Shift state a few times due to low seed entropy
  21. for (int i = 0; i < 4; i++) {
  22. rng();
  23. }
  24. }
  25. Xoroshiro128Plus& local() {
  26. return rng;
  27. }
  28. } // namespace random
  29. } // namespace rack