mxnet
thread_local.h
Go to the documentation of this file.
1 
6 #ifndef DMLC_THREAD_LOCAL_H_
7 #define DMLC_THREAD_LOCAL_H_
8 
9 #include <mutex>
10 #include <memory>
11 #include <vector>
12 #include "./base.h"
13 
14 namespace dmlc {
15 
16 // macro hanlding for threadlocal variables
17 #ifdef __GNUC__
18  #define MX_THREAD_LOCAL __thread
19 #elif __STDC_VERSION__ >= 201112L
20  #define MX_THREAD_LOCAL _Thread_local
21 #elif defined(_MSC_VER)
22  #define MX_THREAD_LOCAL __declspec(thread)
23 #endif
24 
25 #if DMLC_CXX11_THREAD_LOCAL == 0
26 #pragma message("Warning: CXX11 thread_local is not formally supported")
27 #endif
28 
34 template<typename T>
36  public:
38  static T* Get() {
39 #if DMLC_CXX11_THREAD_LOCAL && DMLC_MODERN_THREAD_LOCAL == 1
40  static thread_local T inst;
41  return &inst;
42 #else
43  static MX_THREAD_LOCAL T* ptr = nullptr;
44  if (ptr == nullptr) {
45  ptr = new T();
46  Singleton()->RegisterDelete(ptr);
47  }
48  return ptr;
49 #endif
50  }
51 
52  private:
54  ThreadLocalStore() {}
56  ~ThreadLocalStore() {
57  for (size_t i = 0; i < data_.size(); ++i) {
58  delete data_[i];
59  }
60  }
62  static ThreadLocalStore<T> *Singleton() {
63  static ThreadLocalStore<T> inst;
64  return &inst;
65  }
70  void RegisterDelete(T *str) {
71  std::unique_lock<std::mutex> lock(mutex_);
72  data_.push_back(str);
73  lock.unlock();
74  }
76  std::mutex mutex_;
78  std::vector<T*> data_;
79 };
80 
81 } // namespace dmlc
82 
83 #endif // DMLC_THREAD_LOCAL_H_
static T * Get()
Definition: thread_local.h:38
A threadlocal store to store threadlocal variables. Will return a thread local singleton of type T...
Definition: thread_local.h:35
namespace for dmlc
Definition: array_view.h:12