Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include "semaphore.hpp"
  4.  
  5. #include <twist/support/compiler.hpp>
  6.  
  7. #include <deque>
  8.  
  9. namespace solutions {
  10.  
  11. template <typename T>
  12. class BufferedChannel {
  13. public:
  14. explicit BufferedChannel(size_t capacity)
  15. : send_semaphore_(capacity), recv_semaphore_(0), mutex_(1) {
  16. }
  17.  
  18. void Send(T item) {
  19. send_semaphore_.Acquire();
  20.  
  21. mutex_.Acquire();
  22. storage_.push_back(std::move(item));
  23. mutex_.Release();
  24.  
  25. recv_semaphore_.Release();
  26. }
  27.  
  28. T Recv() {
  29. recv_semaphore_.Acquire();
  30.  
  31. mutex_.Acquire();
  32. T item = storage_.front();
  33. storage_.pop_front();
  34. mutex_.Release();
  35.  
  36. send_semaphore_.Release();
  37. return item;
  38. }
  39.  
  40. private:
  41. std::deque<T> storage_;
  42. Semaphore send_semaphore_;
  43. Semaphore recv_semaphore_;
  44. Semaphore mutex_;
  45. };
  46.  
  47. } // namespace solutions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement