From 93ffedc620e1df2b0007fdd334c1319427502ea1 Mon Sep 17 00:00:00 2001 From: Michael Wallner Date: Fri, 30 Oct 2020 13:37:41 +0100 Subject: [PATCH] thread safe randoms --- test/lib/random.cpp | 10 ++++++++++ test/lib/random.hpp | 17 ++++++++--------- test/setup.cpp | 3 +++ 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/test/lib/random.cpp b/test/lib/random.cpp index 6aab8875..1d9a20c9 100644 --- a/test/lib/random.cpp +++ b/test/lib/random.cpp @@ -3,6 +3,16 @@ #include // getpid() +mt19937_64 rnd_eng; +mutex rnd_mtx; + +void random_setup() { + using namespace chrono; + + auto time = duration_cast(system_clock::now().time_since_epoch()); + rnd_eng.seed(static_cast(time.count())); +} + unsigned random_port() { do { auto port = random_num(5000, 32000); diff --git a/test/lib/random.hpp b/test/lib/random.hpp index 723146a9..322de6af 100644 --- a/test/lib/random.hpp +++ b/test/lib/random.hpp @@ -22,22 +22,21 @@ #include #include #include +#include using namespace std; using kv_pair = pair; -template -enable_if_t, T> random_num(T min, T max) { - using namespace chrono; - using rnd = mt19937_64; - using dst = uniform_int_distribution; +extern mt19937_64 rnd_eng; +extern mutex rnd_mtx; - static auto time = duration_cast(system_clock::now().time_since_epoch()); - static auto seed = static_cast(time.count()); - static auto rgen = rnd{seed}; +void random_setup(); - return dst(min, max)(rgen); +template +enable_if_t, T> random_num(T min, T max) { + lock_guard m{rnd_mtx}; + return uniform_int_distribution(min, max)(rnd_eng); } unsigned random_port(); diff --git a/test/setup.cpp b/test/setup.cpp index 9591a356..a0325af5 100644 --- a/test/setup.cpp +++ b/test/setup.cpp @@ -1,5 +1,6 @@ #include "mem_config.h" #include "test/lib/env.hpp" +#include "test/lib/random.hpp" #include #include #include @@ -78,6 +79,8 @@ static inline void setup_sasl() { #endif int setup(int &, char ***argv) { + random_setup(); + setup_signals(); setup_asan(*argv); setup_sasl(); -- 2.30.2