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

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


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