我有很多线程(产生请求对象),我有一个工作线程,每个请求产生响应。我使用map来使用key是一个生产者的id,值是线程安全队列所以我可以从基于id的工作线程推送到适当的队列。 我发现这个线程安全映射的实现,它保存了对id,共享队列。我的问题是(我没有多线程经验)如何从工作线程读取所有键的所有队列。 我可以尝试使用wait_and_pop或者实现方法,该方法只返回队列的所有共享指针的列表,解锁然后迭代。是否有第三部分或者提升相似,使用相同的界面映射,例如从stl但是线程安全?
#ifndef THREADSAFE_MAP_HPP
#define THREADSAFE_MAP_HPP
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <map>
template<typename Key, typename Data>
class ConcurrentMap
{
public:
ConcurrentMap(void){};
~ConcurrentMap(void){};
void clear() {
boost::mutex::scoped_lock lock(mMutex);
mQueue.clear();
}
bool contains(Key const& key) {
boost::mutex::scoped_lock lock(mMutex);
typename std::map<Key, Data>::iterator itr = mQueue.find(key);
return (itr != mQueue.end());
}
bool erase(Key const& key) {
boost::mutex::scoped_lock lock(mMutex);
size_t n = mQueue.erase(key);
return (n > 0);
}
void push(Key const& key, Data const& data) {
boost::mutex::scoped_lock lock(mMutex);
mQueue[key] = data;
lock.unlock();
mCondition.notify_one();
}
bool empty() const {
boost::mutex::scoped_lock lock(mMutex);
return mQueue.empty();
}
bool get(Key const& key, Data& popped_value) {
boost::mutex::scoped_lock lock(mMutex);
typename std::map<Key, Data>::iterator itr = mQueue.find(key);
if (itr == mQueue.end())
return false;
popped_value = mQueue[key];
return true;
}
bool try_pop(Key const& key, Data& popped_value) {
boost::mutex::scoped_lock lock(mMutex);
typename std::map<Key, Data>::iterator itr = mQueue.find(key);
if (itr == mQueue.end())
return false;
popped_value = mQueue[key];
mQueue.erase(key);
return true;
}
void wait_and_pop(Key const& key, Data& popped_value) {
boost::mutex::scoped_lock lock(mMutex);
typename std::map<Key, Data>::iterator itr;
while(mQueue.find(key) == mQueue.end()) {
mCondition.wait(lock);
}
popped_value = mQueue[key];
mQueue.erase(key);
}
private:
std::map<Key, Data> mQueue;
mutable boost::mutex mMutex;
boost::condition_variable mCondition;
};
#endif // THREADSAFE_MAP_HPP