c++ - 如何避免重复代码,包括 std::map 和 std::mutex

标签 c++

我有一个包含映射和互斥量的类。在每个成员函数中,互斥锁保护映射免受多个线程访问此类对象的影响,例如:

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;
};

是否有一种优雅的方法来避免重复代码?

最佳答案

您可以像这样使用代理和 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";
}

关于c++ - 如何避免重复代码,包括 std::map 和 std::mutex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22758129/

相关文章:

c++ - 如何使用opencv c++的聚类根据面积和高度对连通分量进行分类

c++ - 如何在托管 C++ 中正确实现返回 "this"的类的方法?

c# - C++ AMP计算与WPF渲染显卡双用性能

c++ - 分配自身时的复制分配运算符

c++ - ReadProcessMemory 始终失败并显示 GLE : 299

c++ - 我怎样才能得到一个 v8 函数来返回一个 C++ 对象?

c++ - 在VS19中调试C++时出现错误代码0x80070002

C++:计数函数只计算第一行

c++ - 在程序启动时自动执行代码而不违反 ODR

c++ - 如何正确使用标签调度来选择构造函数