|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#ifndef OPENCV_GAPI_EXECUTOR_CONC_QUEUE_HPP
|
|
|
#define OPENCV_GAPI_EXECUTOR_CONC_QUEUE_HPP
|
|
|
|
|
|
#include <queue>
|
|
|
#include <mutex>
|
|
|
#include <condition_variable>
|
|
|
|
|
|
#include <opencv2/gapi/own/assert.hpp>
|
|
|
|
|
|
namespace cv {
|
|
|
namespace gapi {
|
|
|
namespace own {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
template<class T>
|
|
|
class concurrent_bounded_queue {
|
|
|
std::queue<T> m_data;
|
|
|
std::size_t m_capacity;
|
|
|
|
|
|
std::mutex m_mutex;
|
|
|
std::condition_variable m_cond_empty;
|
|
|
std::condition_variable m_cond_full;
|
|
|
|
|
|
void unsafe_pop(T &t);
|
|
|
|
|
|
public:
|
|
|
concurrent_bounded_queue() : m_capacity(0) {}
|
|
|
concurrent_bounded_queue(const concurrent_bounded_queue<T> &cc)
|
|
|
: m_data(cc.m_data), m_capacity(cc.m_capacity) {
|
|
|
|
|
|
}
|
|
|
concurrent_bounded_queue(concurrent_bounded_queue<T> &&cc)
|
|
|
: m_data(std::move(cc.m_data)), m_capacity(cc.m_capacity) {
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
void push(const T &t);
|
|
|
void pop(T &t);
|
|
|
bool try_pop(T &t);
|
|
|
|
|
|
void set_capacity(std::size_t capacity);
|
|
|
|
|
|
|
|
|
void clear();
|
|
|
};
|
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
void concurrent_bounded_queue<T>::unsafe_pop(T &t) {
|
|
|
GAPI_Assert(!m_data.empty());
|
|
|
t = m_data.front();
|
|
|
m_data.pop();
|
|
|
}
|
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
void concurrent_bounded_queue<T>::push(const T& t) {
|
|
|
std::unique_lock<std::mutex> lock(m_mutex);
|
|
|
|
|
|
if (m_capacity && m_capacity == m_data.size()) {
|
|
|
|
|
|
m_cond_full.wait(lock, [&](){return m_capacity > m_data.size();});
|
|
|
GAPI_Assert(m_capacity > m_data.size());
|
|
|
}
|
|
|
m_data.push(t);
|
|
|
lock.unlock();
|
|
|
m_cond_empty.notify_one();
|
|
|
}
|
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
void concurrent_bounded_queue<T>::pop(T &t) {
|
|
|
std::unique_lock<std::mutex> lock(m_mutex);
|
|
|
if (m_data.empty()) {
|
|
|
|
|
|
m_cond_empty.wait(lock, [&](){return !m_data.empty();});
|
|
|
}
|
|
|
unsafe_pop(t);
|
|
|
lock.unlock();
|
|
|
m_cond_full.notify_one();
|
|
|
}
|
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
bool concurrent_bounded_queue<T>::try_pop(T &t) {
|
|
|
std::unique_lock<std::mutex> lock(m_mutex);
|
|
|
if (m_data.empty()) {
|
|
|
|
|
|
return false;
|
|
|
}
|
|
|
unsafe_pop(t);
|
|
|
lock.unlock();
|
|
|
m_cond_full.notify_one();
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
void concurrent_bounded_queue<T>::set_capacity(std::size_t capacity) {
|
|
|
GAPI_Assert(m_data.empty());
|
|
|
GAPI_Assert(m_capacity == 0u);
|
|
|
GAPI_Assert(capacity != 0u);
|
|
|
m_capacity = capacity;
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
void concurrent_bounded_queue<T>::clear() {
|
|
|
m_data = std::queue<T>{};
|
|
|
}
|
|
|
|
|
|
}}}
|
|
|
|
|
|
#endif
|
|
|
|