Reputation: 4681
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:
https://github.com/cameron314/concurrentqueue
But I'd rather stick with something standard if I can help it.
Upvotes: 1
Views: 109
Reputation: 24403
What are you proposing is concurrency 101. You should look into some other libraries.
Upvotes: 3
Reputation: 249303
Better would be to use an multiple-producer, multiple-consumer queue. Many implementations exist, e.g. https://github.com/facebook/folly/blob/master/folly/MPMCQueue.h or https://github.com/brycelelbach/boost.lockfree/blob/master/boost/lockfree/deque.hpp
Upvotes: 2