Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <twist/stdlike/mutex.hpp>
  4. #include <twist/stdlike/condition_variable.hpp>
  5. #include <twist/support/locking.hpp>
  6.  
  7. #include <cstddef>
  8.  
  9. #include <iostream>
  10.  
  11. namespace solutions {
  12.  
  13. class CyclicBarrier {
  14. public:
  15. explicit CyclicBarrier(size_t num_threads) {
  16. target_threads_num = num_threads;
  17. cur_threads_num = 0;
  18. should_wake = false;
  19. left_to_awake = 0;
  20. }
  21.  
  22. void PassThrough() {
  23. std::cout<<"left_to_awake = "<<left_to_awake<<"\n";
  24. std::unique_lock<twist::mutex> locker(mu);
  25.  
  26. if(left_to_awake == 0){
  27. should_wake = false;
  28. }
  29.  
  30. cur_threads_num ++;
  31.  
  32. if(cur_threads_num == target_threads_num){
  33. should_wake = true;
  34. cur_threads_num = 0;
  35. left_to_awake = target_threads_num;
  36. locker.unlock();
  37. cond.notify_all();
  38. }
  39. else{
  40. while(!(should_wake && left_to_awake == 0)) {
  41. cond.wait(locker);
  42. }
  43. locker.unlock();
  44. }
  45.  
  46. left_to_awake--;
  47. }
  48.  
  49. private:
  50. size_t target_threads_num;
  51. size_t cur_threads_num;
  52. twist::condition_variable cond;
  53.  
  54. twist::mutex mu;
  55. bool should_wake;
  56. int left_to_awake;
  57. };
  58.  
  59. } // namespace solutions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement