Last active
September 18, 2019 02:02
-
-
Save hewumars/e91095f902350261272af68019d39dac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************ | |
* 存放yuv数据的全局队列 | |
* ThreadSafeQueue<shared_ptr<VideoImageParaT>> yuv_image_queue(kImageDataQueueSize); | |
**************/ | |
#ifndef THREAD_SAFE_QUEUE_H_ | |
#define THREAD_SAFE_QUEUE_H_ | |
#include <mutex> | |
#include <queue> | |
template<typename T> | |
class ThreadSafeQueue { | |
public: | |
/** | |
* @brief ThreadSafeQueue constructor | |
* @param [in] capacity: the queue capacity | |
*/ | |
ThreadSafeQueue(int capacity) { | |
// check the input value: capacity is valid | |
if (capacity >= kMinQueueCapacity && capacity <= kMaxQueueCapacity) { | |
queue_capacity = capacity; | |
} else { // the input value: capacity is invalid, set the default value | |
queue_capacity = kDefaultQueueCapacity; | |
} | |
} | |
/** | |
* @brief ThreadSafeQueue constructor | |
*/ | |
ThreadSafeQueue() { | |
queue_capacity = kDefaultQueueCapacity; | |
} | |
/** | |
* @brief ThreadSafeQueue destructor | |
*/ | |
~ThreadSafeQueue() = default; | |
/** | |
* @brief push data to queue | |
* @param [in] input_value: the value will push to the queue | |
* @return true: success to push data; false: fail to push data | |
*/ | |
bool Push(T input_value) { | |
std::lock_guard<std::mutex> lock(mutex_); | |
// check current size is less than capacity | |
if (queue_.size() < queue_capacity) { | |
queue_.push(input_value); | |
return true; | |
} | |
return false; | |
} | |
/** | |
* @brief pop data from queue | |
* @return true: success to pop data; false: fail to pop data | |
*/ | |
T Pop() { | |
std::lock_guard<std::mutex> lock(mutex_); | |
if (queue_.empty()) { // check the queue is empty | |
return nullptr; | |
} | |
T tmp_ptr = queue_.front(); | |
queue_.pop(); | |
return tmp_ptr; | |
} | |
/** | |
* @brief check the queue is empty | |
* @return true: the queue is empty; false: the queue is not empty | |
*/ | |
bool empty() { | |
std::lock_guard<std::mutex> lock(mutex_); | |
return queue_.empty(); | |
} | |
/** | |
* @brief get the queue size | |
* @return the queue size | |
*/ | |
int size() { | |
std::lock_guard<std::mutex> lock(mutex_); | |
return queue_.size(); | |
} | |
private: | |
std::queue<T> queue_; // the queue | |
int queue_capacity; // queue capacity | |
mutable std::mutex mutex_; // the mutex value | |
const int kMinQueueCapacity = 1; // the minimum queue capacity | |
const int kMaxQueueCapacity = 10000; // the maximum queue capacity | |
const int kDefaultQueueCapacity = 10; // default queue capacity | |
}; | |
#endif /* THREAD_SAFE_QUEUE_H_ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment