1
0
mirror of synced 2025-04-19 00:24:02 +03:00

Make random_string() thread-safe (#2110)

By making the random engine thread_local, each thread now has its own
independent random sequence, ensuring safe concurrent access.
Additionally, using an immediately invoked lambda expression to
initialize the engine eliminates the need for separate static seed
variables.
This commit is contained in:
Florian Albrechtskirchinger 2025-03-13 17:44:43 +01:00 committed by GitHub
parent 94a4028821
commit 2eaa2ea64f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -5100,16 +5100,15 @@ inline std::string random_string(size_t length) {
constexpr const char data[] = constexpr const char data[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// std::random_device might actually be deterministic on some static thread_local std::mt19937 engine([]() {
// platforms, but due to lack of support in the c++ standard library, // std::random_device might actually be deterministic on some
// doing better requires either some ugly hacks or breaking portability. // platforms, but due to lack of support in the c++ standard library,
static std::random_device seed_gen; // doing better requires either some ugly hacks or breaking portability.
std::random_device seed_gen;
// Request 128 bits of entropy for initialization // Request 128 bits of entropy for initialization
static std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
seed_gen()}; return std::mt19937(seed_sequence);
}());
static std::mt19937 engine(seed_sequence);
std::string result; std::string result;
for (size_t i = 0; i < length; i++) { for (size_t i = 0; i < length; i++) {