| Colin Cross | 7add50d | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 1 | /* | 
|  | 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 |  | 
|  | 25 | class Semaphore { | 
|  | 26 | public: | 
|  | 27 | Semaphore(int count = 0) : count_(count) {} | 
|  | 28 | ~Semaphore() = default; | 
|  | 29 |  | 
|  | 30 | void Wait(std::chrono::milliseconds ms) { | 
|  | 31 | std::unique_lock<std::mutex> lk(m_); | 
|  | 32 | cv_.wait_for(lk, ms, [&]{ | 
|  | 33 | if (count_ > 0) { | 
|  | 34 | count_--; | 
|  | 35 | return true; | 
|  | 36 | } | 
|  | 37 | return false; | 
|  | 38 | }); | 
|  | 39 | } | 
|  | 40 | void Post() { | 
|  | 41 | { | 
|  | 42 | std::lock_guard<std::mutex> lk(m_); | 
|  | 43 | count_++; | 
|  | 44 | } | 
|  | 45 | cv_.notify_one(); | 
|  | 46 | } | 
|  | 47 | private: | 
|  | 48 | DISALLOW_COPY_AND_ASSIGN(Semaphore); | 
|  | 49 |  | 
|  | 50 | int count_; | 
|  | 51 | std::mutex m_; | 
|  | 52 | std::condition_variable cv_; | 
|  | 53 | }; | 
|  | 54 |  | 
|  | 55 |  | 
|  | 56 | #endif // LIBMEMUNREACHABLE_SEMAPHORE_H_ |