Locks.cpp 1.9 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

Y
Yu Yang 已提交
15
#include "paddle/utils/Locks.h"
Y
Yu Yang 已提交
16 17 18 19 20 21 22 23 24
#include <semaphore.h>
#include <unistd.h>

namespace paddle {
class SemaphorePrivate {
public:
  sem_t sem;
};

25
Semaphore::Semaphore(int initValue) : m(new SemaphorePrivate()) {
Y
Yu Yang 已提交
26 27 28
  sem_init(&m->sem, 0, initValue);
}

29
Semaphore::~Semaphore() { sem_destroy(&m->sem); }
Y
Yu Yang 已提交
30 31 32 33 34

bool Semaphore::timeWait(struct timespec* ts) {
  return (0 == sem_timedwait(&m->sem, ts));
}

35
void Semaphore::wait() { sem_wait(&m->sem); }
Y
Yu Yang 已提交
36

37
void Semaphore::post() { sem_post(&m->sem); }
Y
Yu Yang 已提交
38 39 40 41 42 43 44 45 46

class SpinLockPrivate {
public:
  inline SpinLockPrivate() { pthread_spin_init(&lock_, 0); }
  inline ~SpinLockPrivate() { pthread_spin_destroy(&lock_); }
  pthread_spinlock_t lock_;
  char padding_[64 - sizeof(pthread_spinlock_t)];
};

47
SpinLock::SpinLock() : m(new SpinLockPrivate()) {}
Y
Yu Yang 已提交
48 49 50

SpinLock::~SpinLock() { delete m; }

51
void SpinLock::lock() { pthread_spin_lock(&m->lock_); }
Y
Yu Yang 已提交
52

53
void SpinLock::unlock() { pthread_spin_unlock(&m->lock_); }
Y
Yu Yang 已提交
54 55 56 57 58 59

class ThreadBarrierPrivate {
public:
  pthread_barrier_t barrier_;
};

60
ThreadBarrier::ThreadBarrier(int count) : m(new ThreadBarrierPrivate()) {
Y
Yu Yang 已提交
61 62 63 64 65 66 67 68
  pthread_barrier_init(&m->barrier_, nullptr, count);
}

ThreadBarrier::~ThreadBarrier() {
  pthread_barrier_destroy(&m->barrier_);
  delete m;
}

69
void ThreadBarrier::wait() { pthread_barrier_wait(&m->barrier_); }
Y
Yu Yang 已提交
70

Y
Yu Yang 已提交
71
}  // namespace paddle