Safe and effective way to put a mutex on a container entry

后端 未结 1 706
别跟我提以往
别跟我提以往 2020-12-15 08:48

C++\'s std::mutex does not have a move constructor. There is a good reason for that. Basically, move constructors themselves are not generally thread safe, and

相关标签:
1条回答
  • 2020-12-15 09:36

    The mutex does not require to be moved:

    Imagine that every row in your map is like:

    template <class T>
    class row
    {
        shared_ptr<mutex> m;
        T data;
        ...
    };
    

    So if your row need to be moved or copied, there is no problem.

    Then, you may access the mutex from every process to access the data.

    Of course, you need a global mutex to perform changes on the whole map: insert / delete / [] / any other operation that change the state of the map.

    EDITED:

    Following a simple example of code with a mutex in every row. (It does not implement anything else that just the data structure)

    #include <memory>
    #include <map>
    #include <mutex>
    
    template <class T>
    class row
    {
        std::shared_ptr<std::mutex> m;
        T data;
    public:
        row( std::shared_ptr<std::mutex> mut): m(mut){};
    };
    
    auto main () -> int
    {
        std::shared_ptr<std::mutex> mut(new std::mutex);
        std::map<int,row<int>> db;
        row<int> a(mut);
        db.insert(std::pair<int, row<int>>(1, a));
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题