ThreadLocal.h 5.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once

#include <pthread.h>
#include <sys/syscall.h>
Y
Yu Yang 已提交
19
#include <sys/types.h>
Z
zhangjinchao01 已提交
20 21 22 23 24
#include <unistd.h>
#include <map>
#include <mutex>
#include <random>
#include "Logging.h"
Y
Yu Yang 已提交
25
#include "Util.h"
Z
zhangjinchao01 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

namespace paddle {

/**
 * Thread local storage for object.
 * Example:
 *
 * Declarartion:
 * ThreadLocal<vector<int>> vec_;
 *
 * Use in thread:
 * vector<int>& vec = *vec; // obtain the thread specific object
 * vec.resize(100);
 *
 * Note that this ThreadLocal will desconstruct all internal data when thread
 * exits
 * This class is suitable for cases when frequently creating and deleting
 * threads.
 *
 * Consider implementing a new ThreadLocal if one needs to frequently create
 * both instances and threads.
 *
 * see also ThreadLocalD
 */
template <class T>
class ThreadLocal {
W
Wu Yi 已提交
52
 public:
Z
zhangjinchao01 已提交
53
  ThreadLocal() {
L
liaogang 已提交
54
    CHECK_EQ(pthread_key_create(&threadSpecificKey_, dataDestructor), 0);
Z
zhangjinchao01 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67
  }
  ~ThreadLocal() { pthread_key_delete(threadSpecificKey_); }

  /**
   * @brief get thread local object.
   * @param if createLocal is true and thread local object is never created,
   * return a new object. Otherwise, return nullptr.
   */
  T* get(bool createLocal = true) {
    T* p = (T*)pthread_getspecific(threadSpecificKey_);
    if (!p && createLocal) {
      p = new T();
      int ret = pthread_setspecific(threadSpecificKey_, p);
L
liaogang 已提交
68
      CHECK_EQ(ret, 0);
Z
zhangjinchao01 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81
    }
    return p;
  }

  /**
   * @brief set (overwrite) thread local object. If there is a thread local
   * object before, the previous object will be destructed before.
   *
   */
  void set(T* p) {
    if (T* q = get(false)) {
      dataDestructor(q);
    }
L
liaogang 已提交
82
    CHECK_EQ(pthread_setspecific(threadSpecificKey_, p), 0);
Z
zhangjinchao01 已提交
83 84 85 86 87 88 89 90 91 92
  }

  /**
   * return reference.
   */
  T& operator*() { return *get(); }

  /**
   * Implicit conversion to T*
   */
93
  operator T*() { return get(); }
Z
zhangjinchao01 已提交
94

W
Wu Yi 已提交
95
 private:
Z
zhangjinchao01 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  static void dataDestructor(void* p) { delete (T*)p; }

  pthread_key_t threadSpecificKey_;
};

/**
 * Almost the same as ThreadLocal, but note that this ThreadLocalD will
 * destruct all internal data when ThreadLocalD instance destructs.
 *
 * This class is suitable for cases when frequently creating and deleting
 * objects.
 *
 * see also ThreadLocal
 *
 * @note The type T must implemented default constructor.
 */
template <class T>
class ThreadLocalD {
W
Wu Yi 已提交
114
 public:
L
liaogang 已提交
115
  ThreadLocalD() { CHECK_EQ(pthread_key_create(&threadSpecificKey_, NULL), 0); }
Z
zhangjinchao01 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129
  ~ThreadLocalD() {
    pthread_key_delete(threadSpecificKey_);
    for (auto t : threadMap_) {
      dataDestructor(t.second);
    }
  }

  /**
   * @brief Get thread local object. If not exists, create new one.
   */
  T* get() {
    T* p = (T*)pthread_getspecific(threadSpecificKey_);
    if (!p) {
      p = new T();
L
liaogang 已提交
130
      CHECK_EQ(pthread_setspecific(threadSpecificKey_, p), 0);
Z
zhangjinchao01 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143
      updateMap(p);
    }
    return p;
  }

  /**
   * @brief Set thread local object. If there is an object create before, the
   * old object will be destructed.
   */
  void set(T* p) {
    if (T* q = (T*)pthread_getspecific(threadSpecificKey_)) {
      dataDestructor(q);
    }
L
liaogang 已提交
144
    CHECK_EQ(pthread_setspecific(threadSpecificKey_, p), 0);
Z
zhangjinchao01 已提交
145 146 147 148 149 150 151 152
    updateMap(p);
  }

  /**
   * @brief Get reference of the thread local object.
   */
  T& operator*() { return *get(); }

W
Wu Yi 已提交
153
 private:
Z
zhangjinchao01 已提交
154 155 156
  static void dataDestructor(void* p) { delete (T*)p; }

  void updateMap(T* p) {
G
gangliao 已提交
157
    pid_t tid = getTID();
L
liaogang 已提交
158
    CHECK_NE(tid, -1);
Z
zhangjinchao01 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    std::lock_guard<std::mutex> guard(mutex_);
    auto ret = threadMap_.insert(std::make_pair(tid, p));
    if (!ret.second) {
      ret.first->second = p;
    }
  }

  pthread_key_t threadSpecificKey_;
  std::mutex mutex_;
  std::map<pid_t, T*> threadMap_;
};

/**
 * @brief Thread-safe C-style random API.
 */
class ThreadLocalRand {
W
Wu Yi 已提交
175
 public:
Z
zhangjinchao01 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  /**
   * initSeed just like srand,
   * called by main thread,
   * init defaultSeed for all thread
   */
  static void initSeed(unsigned int seed) { defaultSeed_ = seed; }

  /**
   * initThreadSeed called by each thread,
   * init seed to defaultSeed + *tid*
   * It should be called after main initSeed and before using rand()
   * It's optional, getSeed will init seed if it's not initialized.
   */
  static void initThreadSeed(int tid) {
    seed_.set(new unsigned int(defaultSeed_ + tid));
  }

  /// thread get seed, then can call rand_r many times.
  /// Caller thread can modify the seed value if it's necessary.
  ///
  /// if flag thread_local_rand_use_global_seed set,
  /// the seed will be set to defaultSeed in thread's first call.
  static unsigned int* getSeed();

  /// like ::rand
  static int rand() { return rand_r(getSeed()); }

  /**
   * Get defaultSeed for all thread.
   */
  static int getDefaultSeed() { return defaultSeed_; }

W
Wu Yi 已提交
208
 protected:
Z
zhangjinchao01 已提交
209 210 211 212 213 214 215 216
  static unsigned int defaultSeed_;
  static ThreadLocal<unsigned int> seed_;
};

/**
 * @brief Thread-safe C++ style random engine.
 */
class ThreadLocalRandomEngine {
W
Wu Yi 已提交
217
 public:
Z
zhangjinchao01 已提交
218 219 220 221 222 223 224
  /**
   * get random_engine for each thread.
   *
   * Engine's seed will be initialized by ThreadLocalRand.
   */
  static std::default_random_engine& get();

W
Wu Yi 已提交
225
 protected:
Z
zhangjinchao01 已提交
226 227 228 229
  static ThreadLocal<std::default_random_engine> engine_;
};

}  // namespace paddle