123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- #ifndef DBQUEUE_H
- #define DBQUEUE_H
- #include <queue>
- #include <mutex>
- #include <memory>
- #include <condition_variable>
- namespace eprosima {
- namespace fastrtps{
- template<class T>
- class DBQueue {
- public:
- DBQueue():
- mForegroundQueue(&mQueueAlpha),
- mBackgroundQueue(&mQueueBeta)
- {}
-
- void Swap()
- {
- std::unique_lock<std::mutex> fgGuard(mForegroundMutex);
- std::unique_lock<std::mutex> bgGuard(mBackgroundMutex);
-
- std::queue<T>().swap(*mForegroundQueue);
- auto* swap = mBackgroundQueue;
- mBackgroundQueue = mForegroundQueue;
- mForegroundQueue = swap;
- }
-
- void Push(const T& item)
- {
- std::unique_lock<std::mutex> guard(mBackgroundMutex);
- mBackgroundQueue->push(item);
- }
-
-
- T& Front()
- {
- std::unique_lock<std::mutex> guard(mForegroundMutex);
- return mForegroundQueue->front();
- }
- const T& Front() const
- {
- std::unique_lock<std::mutex> guard(mForegroundMutex);
- return mForegroundQueue->front();
- }
-
- void Pop()
- {
- std::unique_lock<std::mutex> guard(mForegroundMutex);
- mForegroundQueue->pop();
- }
-
- bool Empty() const
- {
- std::unique_lock<std::mutex> guard(mForegroundMutex);
- return mForegroundQueue->empty();
- }
-
- bool BothEmpty() const
- {
- std::unique_lock<std::mutex> guard(mForegroundMutex);
- std::unique_lock<std::mutex> bgGuard(mBackgroundMutex);
- return mForegroundQueue->empty() && mBackgroundQueue->empty();
- }
-
- size_t Size() const
- {
- std::unique_lock<std::mutex> guard(mForegroundMutex);
- return mForegroundQueue->size();
- }
-
- void Clear()
- {
- std::unique_lock<std::mutex> fgGuard(mForegroundMutex);
- std::unique_lock<std::mutex> bgGuard(mBackgroundMutex);
- std::queue<T>().swap(*mForegroundQueue);
- std::queue<T>().swap(*mBackgroundQueue);
- }
- private:
-
- std::queue<T> mQueueAlpha;
- std::queue<T> mQueueBeta;
-
- std::queue<T>* mForegroundQueue;
- std::queue<T>* mBackgroundQueue;
- mutable std::mutex mForegroundMutex;
- mutable std::mutex mBackgroundMutex;
- };
- }
- }
- #endif
|