1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
template<typename T>
class threadSafeQueue{
private:
mutable std::mutex mut;
std::queue<T> dataQueue;
std::condition_variable dataCond;
public:
threadSafeQueue(){}
void push(T newValue){
std::lock_guard<std::mutex> lk(mut);
dataQueue.push(std::move(newValue));
dataCond.notify_one();
}
void wait_and_pop(T& value){
std::unique_lock<std::mutex> lk(mut);
dataCond.wait(lk, [this]{return !dataQueue.empty();});
value=std::move(dataQueue.front());
dataQueue.pop();
}
std::shared_ptr<T> wait_and_pop(){
std::unique_lock<std::mutex> lk(mut);
dataCond.wait(lk, [this]{return !dataQueue.empty();});
std::shared_ptr<T> res(std::make_shared<T>(std::move(dataQueue.front())));
dataQueue.pop();
return res;
}
bool try_pop(T& value){
std::lock_guard<std::mutex> lk(mut);
if(dataQueue.empty()) return false;
value=std::move(dataQueue.front());
dataQueue.pop();
return true;
}
std::shared_ptr<T> try_pop(){
std::lock_guard<std::mutex> lk(mut);
if(dataQueue.empty()) return std::shared_ptr<T>();
std::shared_ptr<T> res(std::make_shared<T>(std::move(dataQueue.front())));
dataQueue.pop();
return res;
}
bool empty() const{
std::lock_guard<std::mutex> lk(mut);
return dataQueue.empty();
}
}; |
Partager