Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <tpcc/stdlike/condition_variable.hpp>
- #include <cstddef>
- #include <mutex>
- namespace tpcc {
- namespace solutions {
- class CyclicBarrier {
- public:
- explicit CyclicBarrier(const size_t num_threads)
- : num_threads_(num_threads), current_thread_count_(num_threads), pass_thread_count_(0) {
- }
- void PassThrough() {
- std::unique_lock<std::mutex> lock(mutex_);
- while (pass_thread_count_ % num_threads_ != 0) { // if thread try to pass new barrier but some threads don't pass previous barrier
- all_threads_arrived_.wait(lock);
- }
- current_thread_count_--;
- while ((current_thread_count_ > 0 && current_thread_count_ != num_threads_)) {
- all_threads_arrived_.wait(lock);
- }
- if (current_thread_count_ == 0) {
- all_threads_arrived_.notify_all();
- }
- pass_thread_count_++; // increment this counter
- if (pass_thread_count_ % num_threads_ == 0) { // if all threads pass the barrier we update current_thread_count_
- current_thread_count_ = num_threads_;
- }
- }
- private:
- size_t num_threads_;
- size_t current_thread_count_;
- size_t pass_thread_count_; // when the thread pass the barrier we increment it
- std::mutex mutex_;
- tpcc::condition_variable all_threads_arrived_;
- };
- } // namespace solutions
- } // namespace tpcc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement