Advertisement
Guest User

Untitled

a guest
Jul 28th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. // this is the class associated to a deque
  2. class DequeEntity {
  3. public:
  4. bool remove(Elem& elem); // simple RAII methods for inserting
  5. void insert(Elem info); // and removing in this deque
  6. size_t size() const { return q.size(); }
  7. bool isEmpty() { return q.empty(); }
  8. private:
  9. std::mutex m;
  10. std::condition_variable write, read;
  11. std::deque<Elem> q;
  12. };
  13.  
  14. // this class contains the three deques
  15. class DequeManager {
  16. public:
  17. void insert(Elem e);
  18. void remove(void); // <--- this is my real struggle
  19. void printQueues(void);
  20. void startRemoverThread(void); // start removerThread; called once
  21.  
  22. private:
  23. std::thread removerThread;
  24. std::array<DequeEntity, 3> deques;
  25. };
  26.  
  27. bool DequeEntity::remove(Elem& elem) {
  28. std::unique_lock<std::mutex> lck(m);
  29. if (read.wait_for(lck, std::chrono::milliseconds(1000),
  30. [this]() { return q.size() > 0; })) {
  31. try {
  32. ic = std::move(q.front());
  33. q.pop_front();
  34. } catch (const std::exception& e) {
  35. debug_red(e.what());
  36. return false;
  37. }
  38. write.notify_one();
  39. return true;
  40. }
  41. else {
  42. // timeout expired, failed to retrieve element from deque
  43. return false;
  44. }
  45. }
  46.  
  47. void DequeManager::remove(void) {
  48. Elem elem;
  49.  
  50. while (true) {
  51. numQueue = 0;
  52. for (auto &q : deques) {
  53. if (q.remove(elem)) {
  54. // do stuff with elem
  55. // if there's more to read, go ahead
  56. while (q.size() > 0) {
  57. Elem elem;
  58. if (q.remove(elem)) {
  59. // do stuff with elem
  60. } else {
  61. // failed to get another element;
  62. // go on next deque
  63. break;
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement