I'm aware that no STL container guarantees thread safety. I also know that it's not terribly difficult to implement with std::lock_guard. However, for what i'm currently doing, I will at least one thread to push things onto a deque and another to take them off. There is no guaranteed number of threads, but I can guarantee that each thread with either push or pull, but not both, if that's at all relevant.
I've been doing something like this:
template<typename T, typename... Args>
class SafeDeque {
std::deque<T, Args...> m_deque;
std::mutex m_mu;
public:
SafeDeque() { }
void push_back(const T& val) {
std::lock_guard<std::mutex> lock(m_mu);
m_deque.push_back(val);
}
void push_front(const T& val) {
std::lock_guard<std::mutex> lock(m_mu);
m_deque.push_front(val);
}
T& back(void) {
std::lock_guard<std::mutex> lock(m_mu);
return m_deque.back();
}
const T& back(void) const {
std::lock_guard<std::mutex> lock(m_mu);
return m_deque.back();
}
T& front(void) {
std::lock_guard<std::mutex> lock(m_mu);
return m_deque.front();
}
const T& front(void) const {
std::lock_guard<std::mutex> lock(m_mu);
return m_deque.front();
}
};
However, this just 'feels' weird on some level. Is there a better way of doing it using only standard C++11/14? I've seen this:
http://ift.tt/10FJ7Pz
But I'd rather stick with something standard if I can help it.
Aucun commentaire:
Enregistrer un commentaire