ATLAS Offline Software
TRandomTLS.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration.
3  */
11 #ifndef ROOTUTILS_TRANDOMTLS_H
12 #define ROOTUTILS_TRANDOMTLS_H
13 
14 #include <atomic>
15 
16 #include "Rtypes.h"
17 #include "boost/thread/tss.hpp"
18 
19 namespace RootUtils {
20 
28  template <class T>
29  class TRandomTLS {
30  public:
38  TRandomTLS(UInt_t seed = 4357) : m_seed(seed) {}
39 
41  ~TRandomTLS() = default;
42 
44  T* get() const;
45  T* operator->() const { return get(); }
46  T& operator*() const { return *get(); }
47 
48  private:
50  mutable boost::thread_specific_ptr<T> m_rand_tls;
51 
53  mutable std::atomic<UInt_t> m_seed;
54  };
55 
56 
57  //
58  // Inline methods
59  //
60 
61  template <class T>
62  inline T* TRandomTLS<T>::get() const
63  {
64  T* random = m_rand_tls.get();
65  if (!random) {
66  random = new T(m_seed > 0 ? m_seed++ : 0);
67  m_rand_tls.reset(random);
68  }
69  return random;
70  }
71 
72 } // namespace RootUtils
73 
74 #endif
RootUtils
Definition: ILogger.h:20
RootUtils::TRandomTLS
Thread-local TRandom generator.
Definition: TRandomTLS.h:29
RootUtils::TRandomTLS::m_rand_tls
boost::thread_specific_ptr< T > m_rand_tls
Thread-local TRandom.
Definition: TRandomTLS.h:50
RootUtils::TRandomTLS::get
T * get() const
Get thread-specific TRandom.
Definition: TRandomTLS.h:62
RootUtils::TRandomTLS::~TRandomTLS
~TRandomTLS()=default
Destructor.
RootUtils::TRandomTLS::operator*
T & operator*() const
Definition: TRandomTLS.h:46
RootUtils::TRandomTLS::m_seed
std::atomic< UInt_t > m_seed
TRandom seed (incremented for each new instance/thread)
Definition: TRandomTLS.h:53
RootUtils::TRandomTLS::operator->
T * operator->() const
Definition: TRandomTLS.h:45
RootUtils::TRandomTLS::TRandomTLS
TRandomTLS(UInt_t seed=4357)
Constructor.
Definition: TRandomTLS.h:38