| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
#ifndef DMLC_THREAD_LOCAL_H_ |
| 7 |
#define DMLC_THREAD_LOCAL_H_ |
| 8 |
|
| 9 |
#include <memory> |
| 10 |
#include <mutex> |
| 11 |
#include <vector> |
| 12 |
|
| 13 |
#include "./base.h" |
| 14 |
|
| 15 |
namespace dmlc { |
| 16 |
|
| 17 |
|
| 18 |
#ifdef __GNUC__ |
| 19 |
#define MX_THREAD_LOCAL __thread |
| 20 |
#elif __STDC_VERSION__ >= 201112L |
| 21 |
#define MX_THREAD_LOCAL _Thread_local |
| 22 |
#elif defined(_MSC_VER) |
| 23 |
#define MX_THREAD_LOCAL __declspec(thread) |
| 24 |
#endif |
| 25 |
|
| 26 |
#if DMLC_CXX11_THREAD_LOCAL == 0 |
| 27 |
#pragma message("Warning: CXX11 thread_local is not formally supported") |
| 28 |
#endif |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
template <typename T> |
| 36 |
class ThreadLocalStore { |
| 37 |
public: |
| 38 |
|
| 39 |
static T *Get() { |
| 40 |
#if DMLC_CXX11_THREAD_LOCAL && DMLC_MODERN_THREAD_LOCAL == 1 |
| 41 |
static thread_local T inst; |
| 42 |
return &inst; |
| 43 |
#else |
| 44 |
static MX_THREAD_LOCAL T *ptr = nullptr; |
| 45 |
if (ptr == nullptr) { |
| 46 |
ptr = new T(); |
| 47 |
|
| 48 |
|
| 49 |
(*Singleton()).RegisterDelete(ptr); |
| 50 |
} |
| 51 |
return ptr; |
| 52 |
#endif |
| 53 |
} |
| 54 |
|
| 55 |
private: |
| 56 |
|
| 57 |
ThreadLocalStore() {} |
| 58 |
|
| 59 |
~ThreadLocalStore() { |
| 60 |
for (size_t i = 0; i < data_.size(); ++i) { |
| 61 |
delete data_[i]; |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
static ThreadLocalStore<T> *Singleton() { |
| 66 |
static ThreadLocalStore<T> inst; |
| 67 |
return &inst; |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
void RegisterDelete(T *str) { |
| 74 |
std::unique_lock<std::mutex> lock(mutex_); |
| 75 |
data_.push_back(str); |
| 76 |
lock.unlock(); |
| 77 |
} |
| 78 |
|
| 79 |
std::mutex mutex_; |
| 80 |
|
| 81 |
std::vector<T *> data_; |
| 82 |
}; |
| 83 |
|
| 84 |
} |
| 85 |
|
| 86 |
#endif |