Program Listing for File queue.h

Return to documentation for file (include\concurrent\queue.h)

/******************************************************************************
© Intel Corporation.

This software and the related documents are Intel copyrighted materials,
and your use of them is governed by the express license under which they
were provided to you ("License"). Unless the License provides otherwise,
you may not use, modify, copy, publish, distribute, disclose or transmit
this software or the related documents without Intel's prior written
permission.


 This software and the related documents are provided as is, with no express
or implied warranties, other than those that are expressly stated in the
License.

******************************************************************************/
#pragma once

#include <algorithm>
#include <deque>
#include <functional>
#include "concurrent/lock.h"

namespace gpa {
namespace concurrent {

template<typename ElementType>
class SimpleConcurrentQueue
{
public:
    void Push(const ElementType& value)
    {
        gpa::ScopedWriteLock guard(&mLock);
        mQueue.push_back(value);
    }

    void Push(ElementType&& value)
    {
        gpa::ScopedWriteLock guard(&mLock);
        mQueue.push_back(value);
    }

    ElementType Pop()
    {
        gpa::ScopedWriteLock guard(&mLock);
        if (mQueue.empty()) {
            return ElementType();
        }
        ElementType elem = mQueue.front();
        mQueue.pop_front();
        return elem;
    }

    bool Empty()
    {
        gpa::ScopedReadLock guard(&mLock);
        return mQueue.empty();
    }

    size_t Size()
    {
        gpa::ScopedReadLock guard(&mLock);
        return mQueue.size();
    }

    size_t RemoveIf(std::function<bool(ElementType&)> pred)
    {
        gpa::ScopedWriteLock guard(&mLock);
        if (mQueue.empty()) {
            return 0;
        }
        size_t count = 0;
        mQueue.erase(std::remove_if(mQueue.begin(), mQueue.end(), [pred, &count](ElementType& element) {
            if (pred(element)) {
                ++count;
                return true;
            }
            return false;
        }));
        return count;
    }

private:
    gpa::RWLock mLock;
    std::deque<ElementType> mQueue;
};

}  // namespace concurrent
}  // namespace gpa