/**
* Copyright (c) 2015 by Contributors
*/
#ifndef PS_INTERNAL_THREADSAFE_QUEUE_H_
#define PS_INTERNAL_THREADSAFE_QUEUE_H_
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <utility>
#include "ps/base.h"
namespace ps {
/** 线程安全队列,允许进队和阻塞弹出 */
/**
* \brief thread-safe queue allowing push and waited pop
*/
template<typename T> class ThreadsafeQueue {
public:
ThreadsafeQueue() { }
~ThreadsafeQueue() { }
/**
* \brief push an value into the end. threadsafe.
* \param new_value the value
*/
void Push(T new_value) {
mu_.lock();
queue_.push(std::move(new_value));
mu_.unlock();
cond_.notify_all();
}
/**
* \brief wait until pop an element from the beginning, threadsafe
* \param value the poped value
*/
void WaitAndPop(T* value) {
std::unique_lock<std::mutex> lk(mu_);
cond_.wait(lk, [this]{return !queue_.empty();});
*value = std::move(queue_.front());
queue_.pop();
}
private:
mutable std::mutex mu_;
std::queue<T> queue_;
std::condition_variable cond_;
};
} // namespace ps
// bool TryPop(T& value) {
// std::lock_guard<std::mutex> lk(mut);
// if(data_queue.empty())
// return false;
// value=std::move(data_queue.front());
// data_queue.pop();
// return true;
// }
#endif // PS_INTERNAL_THREADSAFE_QUEUE_H_
ps-lite源码分析: include/ps/internal/threadsafe_queue.h
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- /*** Copyright (c) 2015 by Contributors*/#ifndef PS_INTE...