ACloudViewer  3.9.4
A Modern Library for 3D Data Processing
Random.cpp
Go to the documentation of this file.
1 // ----------------------------------------------------------------------------
2 // - CloudViewer: www.cloudViewer.org -
3 // ----------------------------------------------------------------------------
4 // Copyright (c) 2018-2024 www.cloudViewer.org
5 // SPDX-License-Identifier: MIT
6 // ----------------------------------------------------------------------------
7 
9 
10 #include <Logging.h>
11 
12 namespace cloudViewer {
13 namespace utility {
14 namespace random {
15 
19 public:
20  RandomContext(RandomContext const&) = delete;
21  void operator=(RandomContext const&) = delete;
22 
25  static RandomContext instance;
26  return instance;
27  }
28 
30  void Seed(const int seed) {
31  seed_ = seed;
32  engine_ = std::mt19937(seed_);
33  }
34 
37  std::mt19937* GetEngine() { return &engine_; }
38 
40  std::mutex* GetMutex() { return &mutex_; }
41 
42 private:
43  RandomContext() {
44  // Randomly seed the seed by default.
45  std::random_device rd;
46  Seed(rd());
47  }
48  int seed_;
49  std::mt19937 engine_;
50  std::mutex mutex_;
51 };
52 
53 void Seed(const int seed) { RandomContext::GetInstance().Seed(seed); }
54 
55 std::mt19937* GetEngine() { return RandomContext::GetInstance().GetEngine(); }
56 
57 std::mutex* GetMutex() { return RandomContext::GetInstance().GetMutex(); }
58 
59 uint32_t RandUint32() {
60  std::lock_guard<std::mutex> lock(*GetMutex());
61  return (*GetEngine())();
62 }
63 
64 } // namespace random
65 } // namespace utility
66 } // namespace cloudViewer
RandomContext(RandomContext const &)=delete
std::mutex * GetMutex()
Get global singleton mutex to protect the engine call.
Definition: Random.cpp:40
void operator=(RandomContext const &)=delete
static RandomContext & GetInstance()
Returns the singleton instance.
Definition: Random.cpp:24
void Seed(const int seed)
Seed the random number generator (globally).
Definition: Random.cpp:30
std::mt19937 * GetEngine()
Definition: Random.cpp:55
void Seed(const int seed)
Set CloudViewer global random seed.
Definition: Random.cpp:53
std::mutex * GetMutex()
Definition: Random.cpp:57
Generic file read and write utility for python interface.