Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // this is the class associated to a deque
- class DequeEntity {
- public:
- bool remove(Elem& elem); // simple RAII methods for inserting
- void insert(Elem info); // and removing in this deque
- size_t size() const { return q.size(); }
- bool isEmpty() { return q.empty(); }
- private:
- std::mutex m;
- std::condition_variable write, read;
- std::deque<Elem> q;
- };
- // this class contains the three deques
- class DequeManager {
- public:
- void insert(Elem e);
- void remove(void); // <--- this is my real struggle
- void printQueues(void);
- void startRemoverThread(void); // start removerThread; called once
- private:
- std::thread removerThread;
- std::array<DequeEntity, 3> deques;
- };
- bool DequeEntity::remove(Elem& elem) {
- std::unique_lock<std::mutex> lck(m);
- if (read.wait_for(lck, std::chrono::milliseconds(1000),
- [this]() { return q.size() > 0; })) {
- try {
- ic = std::move(q.front());
- q.pop_front();
- } catch (const std::exception& e) {
- debug_red(e.what());
- return false;
- }
- write.notify_one();
- return true;
- }
- else {
- // timeout expired, failed to retrieve element from deque
- return false;
- }
- }
- void DequeManager::remove(void) {
- Elem elem;
- while (true) {
- numQueue = 0;
- for (auto &q : deques) {
- if (q.remove(elem)) {
- // do stuff with elem
- // if there's more to read, go ahead
- while (q.size() > 0) {
- Elem elem;
- if (q.remove(elem)) {
- // do stuff with elem
- } else {
- // failed to get another element;
- // go on next deque
- break;
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement