OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * This file is part of Adblock Plus <https://adblockplus.org/>, |
| 3 * Copyright (C) 2006-2016 Eyeo GmbH |
| 4 * |
| 5 * Adblock Plus is free software: you can redistribute it and/or modify |
| 6 * it under the terms of the GNU General Public License version 3 as |
| 7 * published by the Free Software Foundation. |
| 8 * |
| 9 * Adblock Plus is distributed in the hope that it will be useful, |
| 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 * GNU General Public License for more details. |
| 13 * |
| 14 * You should have received a copy of the GNU General Public License |
| 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
| 16 */ |
| 17 |
| 18 #if !defined(LATCH_H) |
| 19 #define LATCH_H |
| 20 |
| 21 #include <condition_variable> |
| 22 #include <mutex> |
| 23 #include <stdexcept> |
| 24 |
| 25 /** |
| 26 * Latch class mimicking the concept in C++ Concurrency TS. |
| 27 * Only some of the member functions are implemented. |
| 28 * |
| 29 * \par Reference |
| 30 * - N3998 C++ Latches and Barriers |
| 31 * http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3998.html |
| 32 */ |
| 33 class Latch |
| 34 { |
| 35 /** |
| 36 * Internal count. |
| 37 * |
| 38 * The synchronization condition is that \c count is zero. |
| 39 */ |
| 40 int count; |
| 41 |
| 42 /** |
| 43 * Mutex protecting the integrity of the count. |
| 44 * This mutex is only used transiently. |
| 45 */ |
| 46 std::mutex m; |
| 47 |
| 48 typedef std::unique_lock<std::mutex> UniqueLockType; |
| 49 |
| 50 /** |
| 51 * Condition variable blocking for Wait(). |
| 52 * |
| 53 * \par Invariant |
| 54 * - If the synchronization condition has not been met, mutexBlocking is locke
d. |
| 55 */ |
| 56 std::condition_variable cv; |
| 57 |
| 58 bool synchronizationCondition() const |
| 59 { |
| 60 return count == 0; |
| 61 } |
| 62 |
| 63 public: |
| 64 /** |
| 65 * Initializes the latch with a count of 'initialCount'. |
| 66 */ |
| 67 Latch(int initialCount) |
| 68 : count(initialCount) |
| 69 {} |
| 70 |
| 71 /** |
| 72 * \par Precondition |
| 73 * - No threads are blocked at the synchronization point. |
| 74 */ |
| 75 ~Latch() {}; |
| 76 |
| 77 /** |
| 78 * Decrements the internal count by 1. |
| 79 * If the count reaches 0 the synchronization condition is reached. |
| 80 */ |
| 81 void Arrive(); |
| 82 |
| 83 /** |
| 84 * Blocks the calling thread at the synchronization point |
| 85 * until the synchronization condition is reached. |
| 86 * If the condition has already been reached, the thread does not block. |
| 87 */ |
| 88 void Wait(); |
| 89 |
| 90 /** |
| 91 * Return the current value of the synchroniztion condition. |
| 92 */ |
| 93 bool TryWait(); |
| 94 }; |
| 95 |
| 96 #endif |
OLD | NEW |