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 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <semaphore.h>
#include <unistd.h>

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

Semaphore::Semaphore(int initValue): m(new SemaphorePrivate()) {
  sem_init(&m->sem, 0, initValue);
}

Semaphore::~Semaphore() {
  sem_destroy(&m->sem);
}

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

void Semaphore::wait() {
Y
Yu Yang 已提交
38
  sem_wait(&m->sem);
Y
Yu Yang 已提交
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
}

void Semaphore::post() {
  sem_post(&m->sem);
}


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)];
};

SpinLock::SpinLock():m(new SpinLockPrivate()) {}


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

void SpinLock::lock() {
  pthread_spin_lock(&m->lock_);
}

void SpinLock::unlock() {
  pthread_spin_unlock(&m->lock_);
}

class ThreadBarrierPrivate {
public:
  pthread_barrier_t barrier_;
};

ThreadBarrier::ThreadBarrier(int count): m(new ThreadBarrierPrivate()) {
  pthread_barrier_init(&m->barrier_, nullptr, count);
}

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

void ThreadBarrier::wait() {
  pthread_barrier_wait(&m->barrier_);
}

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