forked from rethinkdb/rethinkdb_rebirth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom.cc
70 lines (53 loc) · 1.72 KB
/
random.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2010-2016 RethinkDB, all rights reserved.
#include "random.hpp"
#include "containers/scoped.hpp"
#include "thread_local.hpp"
rng_t::rng_t()
: m_mt19937(std::random_device{}()) {
}
rng_t::rng_t(uint64_t seed)
: m_mt19937(seed) {
}
int rng_t::randint(int n) {
assert_thread();
guarantee(n > 0, "non-positive argument for randint's [0, n) interval");
// `std::uniform_int_distribution` operates on [a, b]
return std::uniform_int_distribution<int>(0, n - 1)(m_mt19937);
}
uint64_t rng_t::randuint64(uint64_t n) {
assert_thread();
guarantee(n > 0, "non-positive argument for randint's [0, n) interval");
// `std::uniform_int_distribution` operates on [a, b]
return std::uniform_int_distribution<uint64_t>(0, n - 1)(m_mt19937);
}
size_t rng_t::randsize(size_t n) {
assert_thread();
guarantee(n > 0, "non-positive argument for randint's [0, n) interval");
// `std::uniform_int_distribution` operates on [a, b]
return std::uniform_int_distribution<size_t>(0, n - 1)(m_mt19937);
}
double rng_t::randdouble() {
assert_thread();
return std::uniform_real_distribution<double>(0, 1)(m_mt19937);
}
TLS_with_init(rng_t*, rng, nullptr)
rng_t *get_TLS_rng() {
// This lazy construction is to ensure that we construct the thread local
// rng_t on the correct thread, instead of creating it on startup.
if (TLS_get_rng() == nullptr) {
TLS_set_rng(new rng_t());
}
return TLS_get_rng();
}
int randint(int n) {
return get_TLS_rng()->randint(n);
}
uint64_t randuint64(uint64_t n) {
return get_TLS_rng()->randuint64(n);
}
size_t randsize(size_t n) {
return get_TLS_rng()->randsize(n);
}
double randdouble() {
return get_TLS_rng()->randdouble();
}