Locks.h 5.8 KB
Newer Older
Z
zhangjinchao01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.

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/time.h>
#include <condition_variable>
#include <mutex>

Y
Yu Yang 已提交
23
#include "DisableCopy.h"
L
liaogang 已提交
24

Z
zhangjinchao01 已提交
25 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
namespace paddle {

/**
 * A simple read-write lock.
 * The RWlock allows a number of readers or at most one writer 
 * at any point in time.
 * The RWlock disable copy.
 *
 * Lock:
 *
 * Use lock() to lock on write mode, no other thread can get it
 * until unlock.
 *
 * Use lock_shared() to lock on read mode, other thread can get
 * it by using the same method lock_shared().
 * 
 * Unlock:
 *
 * Use unlock() to unlock the lock.
 */
class RWLock {
public:
  RWLock() { pthread_rwlock_init(&rwlock_, NULL); }
  ~RWLock() { pthread_rwlock_destroy(&rwlock_); }
  RWLock(const RWLock&) = delete;
  RWLock& operator=(const RWLock&) = delete;

  /**
   * @brief lock on write mode.
   * @note the method will block the thread, if failed to get the lock.
   */
  // std::mutex interface
  void lock() { pthread_rwlock_wrlock(&rwlock_); }
  /**
   * @brief lock on read mode.
   * @note if another thread is writing, it can't get the lock,
   * and will block the thread.
   */
  void lock_shared() { pthread_rwlock_rdlock(&rwlock_); }
  void unlock() { pthread_rwlock_unlock(&rwlock_); }

protected:
  pthread_rwlock_t rwlock_;
};

/**
 * The ReadLockGuard is a read mode RWLock 
 * using RAII management mechanism. 
 */
class ReadLockGuard {
public:
  /**
   * @brief Construct Function. Lock on rwlock in read mode. 
   */
  explicit ReadLockGuard(RWLock& rwlock) : rwlock_(&rwlock) {
    rwlock_->lock_shared();
  }

  /**
   * @brief Destruct Function.
   * @note This method just unlock the read mode rwlock, 
   * won't destroy the lock.
   */
  ~ReadLockGuard() { rwlock_->unlock(); }

protected:
  RWLock* rwlock_;
};

/**
 * A simple wrapper for spin lock.
 * The lock() method of SpinLock is busy-waiting
 * which means it will keep trying to lock until lock on successfully.
 * The SpinLock disable copy.
 */
Y
Yu Yang 已提交
100
class SpinLockPrivate;
Z
zhangjinchao01 已提交
101 102
class SpinLock {
public:
Y
Yu Yang 已提交
103 104 105
  DISABLE_COPY(SpinLock);
  SpinLock();
  ~SpinLock();
Z
zhangjinchao01 已提交
106 107

  // std::mutext interface
Y
Yu Yang 已提交
108 109
  void lock();
  void unlock();
Z
zhangjinchao01 已提交
110

Y
Yu Yang 已提交
111 112
private:
  SpinLockPrivate* m;
Z
zhangjinchao01 已提交
113 114 115 116 117
};

/**
 * A simple wapper of semaphore which can only be shared in the same process.
 */
Y
Yu Yang 已提交
118
class SemaphorePrivate;
L
liaogang 已提交
119 120
class Semaphore {
public:
Y
Yu Yang 已提交
121 122 123
  //! Disable copy & assign
  Semaphore(const Semaphore& other) = delete;
  Semaphore& operator= (const Semaphore&& other) = delete;
L
liaogang 已提交
124

Y
Yu Yang 已提交
125 126 127
  //! Enable move.
  Semaphore(Semaphore&& other): m(std::move(other.m)) {
  }
L
liaogang 已提交
128

Z
zhangjinchao01 已提交
129 130 131 132 133 134
public:
  /**
   * @brief Construct Function. 
   * @param[in] initValue the initial value of the 
   * semaphore, default 0.
   */
Y
Yu Yang 已提交
135
  explicit Semaphore(int initValue = 0);
Z
zhangjinchao01 已提交
136

Y
Yu Yang 已提交
137
  ~Semaphore();
Z
zhangjinchao01 已提交
138 139 140 141 142 143 144 145 146

  /**
   * @brief The same as wait(), except if the decrement can not 
   * be performed until ts return false install of blocking.
   * @param[in] ts an absolute timeout in seconds and nanoseconds 
   * since the Epoch 1970-01-01 00:00:00 +0000(UTC).
   * @return ture if the decrement proceeds before ts, 
   * else return false.
   */
Y
Yu Yang 已提交
147
  bool timeWait(struct timespec* ts);
Z
zhangjinchao01 已提交
148 149 150 151

  /**
   * @brief decrement the semaphore. If the semaphore's value is 0, then call blocks.
   */
Y
Yu Yang 已提交
152
  void wait();
Z
zhangjinchao01 已提交
153 154 155 156 157

  /**
   * @brief increment the semaphore. If the semaphore's value 
   * greater than 0, wake up a thread blocked in wait().
   */
Y
Yu Yang 已提交
158
  void post();
Z
zhangjinchao01 已提交
159

Y
Yu Yang 已提交
160 161
private:
  SemaphorePrivate* m;
Z
zhangjinchao01 已提交
162 163 164 165 166 167
};

/**
 * A simple wrapper of thread barrier.
 * The ThreadBarrier disable copy.
 */
Y
Yu Yang 已提交
168
class ThreadBarrierPrivate;
Z
zhangjinchao01 已提交
169 170
class ThreadBarrier {
public:
Y
Yu Yang 已提交
171 172
  DISABLE_COPY(ThreadBarrier);

Z
zhangjinchao01 已提交
173 174 175 176
  /**
   * @brief Construct Function. Initialize the barrier should
   * wait for count threads in wait().
   */
Y
Yu Yang 已提交
177 178
  explicit ThreadBarrier(int count);
  ~ThreadBarrier();
Z
zhangjinchao01 已提交
179 180 181 182 183 184 185

  /**
   * @brief . 
   * If there were count - 1 threads waiting before, 
   * then wake up all the count - 1 threads and continue run together. 
   * Else block the thread until waked by other thread .
   */
Y
Yu Yang 已提交
186
  void wait();
Z
zhangjinchao01 已提交
187

Y
Yu Yang 已提交
188 189
private:
  ThreadBarrierPrivate* m;
Z
zhangjinchao01 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
};

/**
 * A wrapper for condition variable with mutex.
 */
class LockedCondition : public std::condition_variable {
public:
  /**
   * @brief execute op and notify one thread which was blocked.
   * @param[in] op a thread can do something in op before notify.
   */
  template <class Op>
  void notify_one(Op op) {
    std::lock_guard<std::mutex> guard(mutex_);
    op();
    std::condition_variable::notify_one();
  }

  /**
   * @brief execute op and notify all the threads which were blocked.
   * @param[in] op a thread can do something in op before notify.
   */
  template <class Op>
  void notify_all(Op op) {
    std::lock_guard<std::mutex> guard(mutex_);
    op();
    std::condition_variable::notify_all();
  }

  /**
   * @brief wait until pred return ture.
   * @tparam Predicate c++ concepts, describes a function object 
   * that takes a single iterator argument 
   * that is dereferenced and used to 
   * return a value testable as a bool.
   * @note pred shall not apply any non-constant function 
   * through the dereferenced iterator. 
   */
  template <class Predicate>
  void wait(Predicate pred) {
    std::unique_lock<std::mutex> lock(mutex_);
    std::condition_variable::wait(lock, pred);
  }

  /**
   * @brief get mutex.
   */
  std::mutex* mutex() { return &mutex_; }

protected:
  std::mutex mutex_;
};

}  // namespace paddle