我有一個類,包括一個地圖和一個互斥體。在每一個成員函數互斥體保護從多個線程訪問這個類的對象可在地圖,爲前:如何避免重複的代碼,包括std :: map和std :: mutex
class bar
{
public:
void hello() {}
void set_something(int x) {}
int get_something(int x, int y) { return x + y; }
};
class foo
{
public:
foo()
{
m_map[0];
m_map[1];
m_map[2];
}
void hello(unsigned int index)
{
std::lock_guard<std::mutex> lock(m_mut);
const auto iter = m_map.find(index);
if (iter != m_map.end())
iter->second.hello();
}
void set_something(unsigned int index, int x)
{
std::lock_guard<std::mutex> lock(m_mut);
const auto iter = m_map.find(index);
if (iter != m_map.end())
iter->second.set_something(x);
}
int get_something(unsigned int index, int x, int y)
{
std::lock_guard<std::mutex> lock(m_mut);
const auto iter = m_map.find(index);
if (iter != m_map.end())
return iter->second.get_something(x, y);
return 0;
}
private:
std::mutex m_mut;
std::map<unsigned int, bar> m_map;
};
有一種優雅的方法,以避免重複的代碼?
使用代理模式爲此非常棒!如果我的示例使用std :: shared_mutex而不是std :: mutex,它也可以工作嗎? – cbel