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

后端 未结 1 718
别跟我提以往
别跟我提以往 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 row
    {
        shared_ptr 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 
    #include 
    #include 
    
    template 
    class row
    {
        std::shared_ptr m;
        T data;
    public:
        row( std::shared_ptr mut): m(mut){};
    };
    
    auto main () -> int
    {
        std::shared_ptr mut(new std::mutex);
        std::map> db;
        row a(mut);
        db.insert(std::pair>(1, a));
        return 0;
    }
    

    0 讨论(0)
提交回复
热议问题