|
| 1 | +//////////////////////////////////////////////////////////////////////////////// |
| 2 | +/// DISCLAIMER |
| 3 | +/// |
| 4 | +/// Copyright 2016 by EMC Corporation, All Rights Reserved |
| 5 | +/// |
| 6 | +/// Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +/// you may not use this file except in compliance with the License. |
| 8 | +/// You may obtain a copy of the License at |
| 9 | +/// |
| 10 | +/// http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +/// |
| 12 | +/// Unless required by applicable law or agreed to in writing, software |
| 13 | +/// distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +/// See the License for the specific language governing permissions and |
| 16 | +/// limitations under the License. |
| 17 | +/// |
| 18 | +/// Copyright holder is EMC Corporation |
| 19 | +/// |
| 20 | +/// @author Valery Mironov |
| 21 | +//////////////////////////////////////////////////////////////////////////////// |
| 22 | + |
| 23 | +#pragma once |
| 24 | + |
| 25 | +#include <atomic> |
| 26 | +#include <condition_variable> |
| 27 | +#include <mutex> |
| 28 | + |
| 29 | +namespace irs { |
| 30 | + |
| 31 | +// TODO(MBkkt) Considered to replace with YACLib |
| 32 | +struct WaitGroup { |
| 33 | + explicit WaitGroup(size_t counter = 0) noexcept : counter_{2 * counter + 1} {} |
| 34 | + |
| 35 | + void Add(size_t counter = 1) noexcept { |
| 36 | + counter_.fetch_add(2 * counter, std::memory_order_relaxed); |
| 37 | + } |
| 38 | + |
| 39 | + void Done(size_t counter = 1) noexcept { |
| 40 | + if (counter_.fetch_sub(2 * counter, std::memory_order_acq_rel) == |
| 41 | + 2 * counter) { |
| 42 | + std::lock_guard lock{m_}; |
| 43 | + cv_.notify_one(); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // Multiple parallel Wait not supported, if needed check YACLib |
| 48 | + void Wait(size_t counter = 0) noexcept { |
| 49 | + if (counter_.fetch_sub(1, std::memory_order_acq_rel) != 1) { |
| 50 | + std::unique_lock lock{m_}; |
| 51 | + while (counter_.load(std::memory_order_acquire) != 0) { |
| 52 | + cv_.wait(lock); |
| 53 | + } |
| 54 | + } |
| 55 | + // We can put acquire here and remove above, but is it worth? |
| 56 | + Reset(counter); |
| 57 | + } |
| 58 | + |
| 59 | + // It shouldn't used for synchronization |
| 60 | + size_t Count() const noexcept { |
| 61 | + return counter_.load(std::memory_order_relaxed) / 2; |
| 62 | + } |
| 63 | + |
| 64 | + void Reset(size_t counter) noexcept { |
| 65 | + counter_.store(2 * counter + 1, std::memory_order_relaxed); |
| 66 | + } |
| 67 | + |
| 68 | + std::mutex& Mutex() noexcept { return m_; } |
| 69 | + |
| 70 | + private: |
| 71 | + std::atomic_size_t counter_; |
| 72 | + std::condition_variable cv_; |
| 73 | + std::mutex m_; |
| 74 | +}; |
| 75 | + |
| 76 | +} // namespace irs |
0 commit comments