So, I have a std::map object which is getting accessed by multiple threads in same time and I decided to use unique_lock to make the map operation safe.
In one of thread's implementation, the map object is getting used by some functions (these functions generally add/remove items from map object), So I wanted to know if defining the unique_lock at the top of parent function would be guarantee the safety ? or i need to add it to every single of those functions ?
void Thread1() { std::unique_lock<std::mutex> ul(mutex); func1(); // map object is getting changed here func2(); // map object is getting changed here }
unique_lockas close to the critical section as possible. That means put it in each offunc1andfunc2only around the parts where your map is accessed. Make sure to put it around read access as well (or use a read/write lock instead this would be an underlyingshared_mutexand a combination ofshared_lockandunique_lockto grab access).