Multi threaded random generator
This commit is contained in:
parent
cbadf5315c
commit
0941d7d364
3 changed files with 33 additions and 0 deletions
|
|
@ -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
|
||||
|
|
|
|||
3
nano/core_test/random.cpp
Normal file
3
nano/core_test/random.cpp
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
#include <nano/lib/random.hpp>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
|
@ -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;
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue