libscheaders/sync_queue.hpp

45 lines
697 B
C++
Raw Permalink Normal View History

2020-03-16 15:11:40 +01:00
//
2020-03-17 11:55:11 +01:00
// sync_queue.h
2020-03-16 15:11:40 +01:00
// adapted from an example from Bjarne Stroustrup
//
2020-03-17 11:55:11 +01:00
#ifndef __sync_queue__
#define __sync_queue__
2020-03-16 15:11:40 +01:00
#include <mutex>
#include <condition_variable>
#include <list>
#include <future>
#include <thread>
namespace sc {
template<typename T>
2020-03-17 11:55:11 +01:00
class sync_queue {
2020-03-16 15:11:40 +01:00
public:
void put(const T& val)
{
std::lock_guard<std::mutex> lck {mtx};
q.push_back(val);
cond.notify_one();
}
T get()
{
std::unique_lock<std::mutex> lck {mtx};
cond.wait(lck, [this]{ return !q.empty(); });
T val {q.front()};
q.pop_front();
return val;
}
private:
std::mutex mtx;
std::condition_variable cond;
std::list<T> q;
};
}
2020-03-17 11:55:11 +01:00
#endif /* defined(__sync_queue__) */