Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <tpcc/stdlike/condition_variable.hpp>
  4. #include <cstddef>
  5. #include <mutex>
  6.  
  7. namespace tpcc {
  8. namespace solutions {
  9.  
  10. class CyclicBarrier {
  11. public:
  12. explicit CyclicBarrier(const size_t num_threads)
  13. : num_threads_(num_threads), current_thread_count_(num_threads), pass_thread_count_(0) {
  14. }
  15.  
  16. void PassThrough() {
  17. std::unique_lock<std::mutex> lock(mutex_);
  18. while (pass_thread_count_ % num_threads_ != 0) { // if thread try to pass new barrier but some threads don't pass previous barrier
  19. all_threads_arrived_.wait(lock);
  20. }
  21. current_thread_count_--;
  22. while ((current_thread_count_ > 0 && current_thread_count_ != num_threads_)) {
  23. all_threads_arrived_.wait(lock);
  24. }
  25. if (current_thread_count_ == 0) {
  26. all_threads_arrived_.notify_all();
  27. }
  28. pass_thread_count_++; // increment this counter
  29. if (pass_thread_count_ % num_threads_ == 0) { // if all threads pass the barrier we update current_thread_count_
  30. current_thread_count_ = num_threads_;
  31. }
  32. }
  33.  
  34. private:
  35. size_t num_threads_;
  36. size_t current_thread_count_;
  37. size_t pass_thread_count_; // when the thread pass the barrier we increment it
  38. std::mutex mutex_;
  39. tpcc::condition_variable all_threads_arrived_;
  40.  
  41. };
  42.  
  43. } // namespace solutions
  44. } // namespace tpcc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement