blob: cd73972665f5042716c5cc77f942d354cf0c3656 [file] [log] [blame]
Colin Crossbcb4ed32016-01-14 15:35:40 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef LIBMEMUNREACHABLE_SEMAPHORE_H_
18#define LIBMEMUNREACHABLE_SEMAPHORE_H_
19
20#include <chrono>
21#include <mutex>
22
23#include "android-base/macros.h"
24
Colin Crossa9939e92017-06-21 13:13:00 -070025namespace android {
26
Colin Crossbcb4ed32016-01-14 15:35:40 -080027class Semaphore {
28 public:
Chih-Hung Hsieh034c4752016-07-12 13:50:44 -070029 explicit Semaphore(int count = 0) : count_(count) {}
Colin Crossbcb4ed32016-01-14 15:35:40 -080030 ~Semaphore() = default;
31
32 void Wait(std::chrono::milliseconds ms) {
33 std::unique_lock<std::mutex> lk(m_);
Colin Crossa83881e2017-06-22 10:50:05 -070034 cv_.wait_for(lk, ms, [&] {
Colin Crossbcb4ed32016-01-14 15:35:40 -080035 if (count_ > 0) {
36 count_--;
37 return true;
38 }
39 return false;
40 });
41 }
42 void Post() {
43 {
44 std::lock_guard<std::mutex> lk(m_);
45 count_++;
46 }
47 cv_.notify_one();
48 }
Colin Crossa83881e2017-06-22 10:50:05 -070049
Colin Crossbcb4ed32016-01-14 15:35:40 -080050 private:
51 DISALLOW_COPY_AND_ASSIGN(Semaphore);
52
53 int count_;
54 std::mutex m_;
55 std::condition_variable cv_;
56};
57
Colin Crossa9939e92017-06-21 13:13:00 -070058} // namespace android
59
Colin Crossa83881e2017-06-22 10:50:05 -070060#endif // LIBMEMUNREACHABLE_SEMAPHORE_H_