You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datasketches.apache.org by "FluorineDog (via GitHub)" <gi...@apache.org> on 2023/03/13 12:08:01 UTC
[GitHub] [datasketches-cpp] FluorineDog commented on a diff in pull request #347: make random utils thread safe
FluorineDog commented on code in PR #347:
URL: https://github.com/apache/datasketches-cpp/pull/347#discussion_r1133830779
##########
common/include/common_defs.hpp:
##########
@@ -36,15 +37,22 @@ enum resize_factor { X1 = 0, X2, X4, X8 };
template<typename A> using AllocChar = typename std::allocator_traits<A>::template rebind_alloc<char>;
template<typename A> using string = std::basic_string<char, std::char_traits<char>, AllocChar<A>>;
-// random bit
-static std::independent_bits_engine<std::mt19937, 1, uint32_t>
- random_bit(static_cast<uint32_t>(std::chrono::system_clock::now().time_since_epoch().count()));
+// thread-safe random bit
+inline uint32_t random_bit()
+{
+ // add additional hash(this_thread::get_id)
+ // to make different threads won't share the same random sequence
+ static thread_local std::independent_bits_engine<std::mt19937, 1, uint32_t>
+ random_bit_impl(static_cast<uint32_t>(std::chrono::system_clock::now().time_since_epoch().count()
+ + std::hash<std::thread::id>{}(std::this_thread::get_id())));
+ return random_bit_impl();
+}
// common random declarations
namespace random_utils {
static std::random_device rd; // possibly unsafe in MinGW with GCC < 9.2
- static std::mt19937_64 rand(rd());
- static std::uniform_real_distribution<> next_double(0.0, 1.0);
+ static thread_local std::mt19937_64 rand(rd());
Review Comment:
It has simliar problem, used by other functions. To make the whole project thread-safe, i think they are necessary.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@datasketches.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datasketches.apache.org
For additional commands, e-mail: commits-help@datasketches.apache.org