Multi threaded random generator

This commit is contained in:
Piotr Wójcik 2024-10-29 09:53:29 +01:00
commit 0941d7d364
3 changed files with 33 additions and 0 deletions

View file

@ -40,6 +40,7 @@ add_executable(
optimistic_scheduler.cpp
processing_queue.cpp
processor_service.cpp
random.cpp
random_pool.cpp
rep_crawler.cpp
receivable.cpp

View file

@ -0,0 +1,3 @@
#include <nano/lib/random.hpp>
#include <gtest/gtest.h>

View file

@ -1,5 +1,6 @@
#pragma once
#include <mutex>
#include <random>
namespace nano
@ -28,4 +29,32 @@ private:
std::random_device device;
std::default_random_engine rng{ device () };
};
/**
* Not safe for any crypto related code, use for non-crypto PRNG only.
* Thread safe.
*/
class random_generator_mt final
{
public:
/// Generate a random number in the range [min, max)
auto random (auto min, auto max)
{
release_assert (min < max);
std::lock_guard<std::mutex> lock{ mutex };
std::uniform_int_distribution<decltype (min)> dist (min, max - 1);
return dist (rng);
}
/// Generate a random number in the range [0, max)
auto random (auto max)
{
return random (decltype (max){ 0 }, max);
}
private:
std::random_device device;
std::default_random_engine rng{ device () };
std::mutex mutex;
};
}