Barrier.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright 2018-present Facebook, Inc.
  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. #pragma once
  17. #include <condition_variable>
  18. #include <mutex>
  19. #include <stdint.h>
  20. namespace folly {
  21. namespace test {
  22. struct Barrier {
  23. explicit Barrier(size_t count) : lock_(), cv_(), count_(count) {}
  24. void wait() {
  25. std::unique_lock<std::mutex> lockHeld(lock_);
  26. auto gen = gen_;
  27. if (++num_ == count_) {
  28. num_ = 0;
  29. gen_++;
  30. cv_.notify_all();
  31. } else {
  32. cv_.wait(lockHeld, [&]() { return gen == gen_; });
  33. }
  34. }
  35. private:
  36. std::mutex lock_;
  37. std::condition_variable cv_;
  38. size_t num_{0};
  39. size_t count_;
  40. size_t gen_{0};
  41. };
  42. } // namespace test
  43. } // namespace folly