92 lines
2.5 KiB
C++
92 lines
2.5 KiB
C++
#ifndef PROJECT_TSQUEUE_H
|
|
#define PROJECT_TSQUEUE_H
|
|
|
|
#include <mutex>
|
|
#include <condition_variable>
|
|
#include <queue>
|
|
|
|
namespace ffcpp {
|
|
|
|
template<typename T> class TSQueue {
|
|
private:
|
|
using LockType = std::lock_guard<std::mutex>;
|
|
|
|
private:
|
|
mutable std::mutex _mutex;
|
|
std::condition_variable _readCond;
|
|
std::condition_variable _writeCond;
|
|
std::queue<std::shared_ptr<T>> _queue;
|
|
size_t _maxSize;
|
|
|
|
public:
|
|
TSQueue(size_t maxSize): _maxSize(maxSize) {
|
|
|
|
}
|
|
|
|
bool empty() const {
|
|
LockType lock(_mutex);
|
|
return _queue.empty();
|
|
}
|
|
|
|
void push(T value) {
|
|
auto data = std::make_shared<T>(std::move(value));
|
|
LockType lock(_mutex);
|
|
_queue.push(data);
|
|
_readCond.notify_one();
|
|
}
|
|
|
|
void pushOrWait(T value) {
|
|
auto data = std::make_shared<T>(std::move(value));
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
if(_queue.size() == _maxSize) {
|
|
_writeCond.wait(lock, [this]{ return _queue.size() < _maxSize; });
|
|
}
|
|
_queue.push(data);
|
|
_readCond.notify_one();
|
|
}
|
|
|
|
|
|
void pushOrWait(std::shared_ptr<T> value) {
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
if(_queue.size() == _maxSize) {
|
|
_writeCond.wait(lock, [this]{ return _queue.size() < _maxSize; });
|
|
}
|
|
_queue.push(value);
|
|
_readCond.notify_one();
|
|
}
|
|
|
|
std::shared_ptr<T> waitAndPop() {
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
_readCond.wait(lock, [this]{ return !_queue.empty(); });
|
|
auto res = _queue.front();
|
|
_queue.pop();
|
|
_writeCond.notify_one();
|
|
return res;
|
|
}
|
|
|
|
std::shared_ptr<T> tryPop() {
|
|
LockType lock(_mutex);
|
|
if(_queue.empty())
|
|
return std::shared_ptr<T>();
|
|
auto res = _queue.front();
|
|
_queue.pop();
|
|
_writeCond.notify_one();
|
|
return res;
|
|
}
|
|
|
|
std::shared_ptr<T> popOrWait() {
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
if(_queue.empty()) {
|
|
_readCond.wait(lock, [this]{ return !_queue.empty(); });
|
|
}
|
|
auto res = _queue.front();
|
|
_queue.pop();
|
|
_writeCond.notify_one();
|
|
return res;
|
|
}
|
|
};
|
|
|
|
}
|
|
|
|
#endif //PROJECT_TSQUEUE_H
|