我有一个类,包括地图和互斥锁。在每个成员函数中,互斥锁保护映射免受访问此类对象的多个线程的影响,例如:
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;
};
是否有一种优雅的方法可以避免重复的代码?
答案 0 :(得分:4)
您可以像这样使用代理和RAII:
#include <iostream>
#include <mutex>
#include <map>
template < typename F, typename S>
struct mutex_map {
std::recursive_mutex m_;
std::map<F,S> map_;
struct Proxy {
Proxy( std::map<F,S> & map, std::recursive_mutex &m ) : map_(&map), lock_(m) {
std::cout << "lock\n";
}
~Proxy() { std::cout << "unlock\n"; }
std::map<F,S>* map_;
std::unique_lock<std::recursive_mutex> lock_;
std::map<F,S>* operator->() { return map_; }
};
Proxy operator->() {
return { map_, m_ };
}
};
int main() {
mutex_map<int, int> mm;
mm->emplace(1, 3);
std::cout << (mm->find(1) == mm->end()) << "\n";
std::cout << (mm->find(2) == mm->end()) << "\n";
}
答案 1 :(得分:2)
您可以将公共部分移动到“do_something”并将仿函数传递给它:
...
void do_something(const std::function<void(bar&)>& func)
{
std::lock_guard<std::mutex> lock(m_mut);
const auto iter = m_map.find(index);
if (iter != m_map.end())
func(std::ref(*iter));
}
int get_something(unsigned int index, int x, int y)
{
do_something(std::bind(&bar::get_something, std::placeholders::_1, index, x, y));
}
...
一个问题 - 您是否需要使用mutex仅保护std :: map或std :: map及其元素?您可以考虑粒度