Skip to content

Commit 4409a68

Browse files
Make random_string() thread-safe
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.
1 parent 94a4028 commit 4409a68

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

httplib.h

+9-10
Original file line numberDiff line numberDiff line change
@@ -5100,16 +5100,15 @@ inline std::string random_string(size_t length) {
51005100
constexpr const char data[] =
51015101
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
51025102

5103-
// std::random_device might actually be deterministic on some
5104-
// platforms, but due to lack of support in the c++ standard library,
5105-
// doing better requires either some ugly hacks or breaking portability.
5106-
static std::random_device seed_gen;
5107-
5108-
// Request 128 bits of entropy for initialization
5109-
static std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(),
5110-
seed_gen()};
5111-
5112-
static std::mt19937 engine(seed_sequence);
5103+
static thread_local std::mt19937 engine([]() {
5104+
// std::random_device might actually be deterministic on some
5105+
// platforms, but due to lack of support in the c++ standard library,
5106+
// doing better requires either some ugly hacks or breaking portability.
5107+
std::random_device seed_gen;
5108+
// Request 128 bits of entropy for initialization
5109+
std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
5110+
return std::mt19937(seed_sequence);
5111+
}());
51135112

51145113
std::string result;
51155114
for (size_t i = 0; i < length; i++) {

0 commit comments

Comments
 (0)