mxnet
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
thread_local.h
Go to the documentation of this file.
1 
6 #ifndef MXNET_COMMON_THREAD_LOCAL_H_
7 #define MXNET_COMMON_THREAD_LOCAL_H_
8 
9 #include <mutex>
10 #include <memory>
11 #include <vector>
12 
13 namespace mxnet {
14 namespace common {
15 
16 // macro hanlding for threadlocal variables
17 #ifdef __GNUC__
18  #define MX_TREAD_LOCAL __thread
19 #elif __STDC_VERSION__ >= 201112L
20  #define MX_TREAD_LOCAL _Thread_local
21 #elif defined(_MSC_VER)
22  #define MX_TREAD_LOCAL __declspec(thread)
23 #endif
24 
25 #ifndef MX_TREAD_LOCAL
26 #message("Warning: Threadlocal is not enabled");
27 #endif
28 
34 template<typename T>
36  public:
38  static T* Get() {
39  static MX_TREAD_LOCAL T* ptr = nullptr;
40  if (ptr == nullptr) {
41  ptr = new T();
42  Singleton()->RegisterDelete(ptr);
43  }
44  return ptr;
45  }
46 
47  private:
49  ThreadLocalStore() {}
51  ~ThreadLocalStore() {
52  for (size_t i = 0; i < data_.size(); ++i) {
53  delete data_[i];
54  }
55  }
57  static ThreadLocalStore<T> *Singleton() {
58  static ThreadLocalStore<T> inst;
59  return &inst;
60  }
65  void RegisterDelete(T *str) {
66  std::unique_lock<std::mutex> lock(mutex_);
67  data_.push_back(str);
68  lock.unlock();
69  }
71  std::mutex mutex_;
73  std::vector<T*> data_;
74 };
75 } // namespace common
76 } // namespace mxnet
77 #endif // MXNET_COMMON_THREAD_LOCAL_H_
A threadlocal store to store threadlocal variables. Will return a thread local singleton of type T...
Definition: thread_local.h:35
static T * Get()
Definition: thread_local.h:38