Debian Codegraph @

src/dmlc-core/include/dmlc/thread_local.h

raw symbols SCIP
1 /*!
2 * Copyright (c) 2015 by Contributors
3 * \file thread_local.h
4 * \brief Portable thread local storage.
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 // macro hanlding for threadlocal variables
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 * \brief A threadlocal store to store threadlocal variables.
32 * Will return a thread local singleton of type T
33 * \tparam T the type we like to store
34 */
35 template <typename T>
36 class ThreadLocalStore {
37 public:
38 /*! \return get a thread local singleton */
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 // Syntactic work-around for the nvcc of the initial cuda v10.1 release,
48 // which fails to compile 'Singleton()->' below. Fixed in v10.1 update 1.
49 (*Singleton()).RegisterDelete(ptr);
50 }
51 return ptr;
52 #endif
53 }
54
55 private:
56 /*! \brief constructor */
57 ThreadLocalStore() {}
58 /*! \brief destructor */
59 ~ThreadLocalStore() {
60 for (size_t i = 0; i < data_.size(); ++i) {
61 delete data_[i];
62 }
63 }
64 /*! \return singleton of the store */
65 static ThreadLocalStore<T> *Singleton() {
66 static ThreadLocalStore<T> inst;
67 return &inst;
68 }
69 /*!
70 * \brief register str for internal deletion
71 * \param str the string pointer
72 */
73 void RegisterDelete(T *str) {
74 std::unique_lock<std::mutex> lock(mutex_);
75 data_.push_back(str);
76 lock.unlock();
77 }
78 /*! \brief internal mutex */
79 std::mutex mutex_;
80 /*!\brief internal data */
81 std::vector<T *> data_;
82 };
83
84 } // namespace dmlc
85
86 #endif // DMLC_THREAD_LOCAL_H_