libstore: make SQLite busy back-off logic portable

Use C++ standard library not Unix functions for sleeping and randomness.

Also change the PRNG seed from `clock()` to `std::random_device` because
there's no good reason not to and this avoids two threads seeding their
PRNG the same.

Upstream-PR: https://github.com/NixOS/nix/pull/10399
Change-Id: I8424e7406366ea8e825d3e93dbb261ce60e3a37f
This commit is contained in:
Lily Ballard
2025-01-31 21:27:48 -08:00
parent 083c6de22c
commit a258f78736
+5 -6
View File
@@ -5,9 +5,10 @@
#include "lix/libutil/signals.hh"
#include "lix/libutil/url.hh"
#include <random>
#include <sqlite3.h>
#include <random>
#include <thread>
namespace nix {
@@ -284,12 +285,10 @@ void handleSQLiteBusy(const SQLiteBusy & e, time_t & nextWarning)
/* Sleep for a while since retrying the transaction right away
is likely to fail again. */
checkInterrupt();
static thread_local std::default_random_engine generator(clock());
static thread_local std::default_random_engine generator(std::random_device{}());
std::uniform_int_distribution<long> uniform_dist(0, 100);
struct timespec t;
t.tv_sec = 0;
t.tv_nsec = uniform_dist(generator) * 1000 * 1000; /* <= 0.1s */
nanosleep(&t, 0);
/* <= 0.1s */
std::this_thread::sleep_for(std::chrono::milliseconds { uniform_dist(generator) });
}
}