Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <twist/stdlike/mutex.hpp>
- #include <twist/stdlike/condition_variable.hpp>
- #include <twist/support/locking.hpp>
- #include <cstddef>
- #include <iostream>
- namespace solutions {
- class CyclicBarrier {
- public:
- explicit CyclicBarrier(size_t num_threads) {
- target_threads_num = num_threads;
- cur_threads_num = 0;
- should_wake = false;
- left_to_awake = 0;
- }
- void PassThrough() {
- std::cout<<"left_to_awake = "<<left_to_awake<<"\n";
- std::unique_lock<twist::mutex> locker(mu);
- if(left_to_awake == 0){
- should_wake = false;
- }
- cur_threads_num ++;
- if(cur_threads_num == target_threads_num){
- should_wake = true;
- cur_threads_num = 0;
- left_to_awake = target_threads_num;
- locker.unlock();
- cond.notify_all();
- }
- else{
- while(!(should_wake && left_to_awake == 0)) {
- cond.wait(locker);
- }
- locker.unlock();
- }
- left_to_awake--;
- }
- private:
- size_t target_threads_num;
- size_t cur_threads_num;
- twist::condition_variable cond;
- twist::mutex mu;
- bool should_wake;
- int left_to_awake;
- };
- } // namespace solutions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement