Question: I have a problem with using `std:map` in my multithread application. I need to lock the map object when thread is writing to this object. Parallely another threads which reading this object should shop until writing process is finish.

Sample code:

```
std::map<int, int> ClientTable;

int write_function() //<-- only one thread uses this function
{
  while(true)
  {
    //lock ClientTable
    ClientTable.insert(std::pair<int, int>(1, 2)); // random values
    //unlock ClientTable

    //thread sleeps for 2 secs
  }
}

int read_function()  //<--- many thread uses this function
{
  while(true)
  {
     int test = ClientTable[2]; // just for test
  }
}

```

How to lock this std::map object and correctly synchronise this threads?

Answer: 
Looks like what you need is a typical read-write lock, allowing any number of readers but a single writer. You can have a look at boost's [shared\_mutex](http://www.boost.org/doc/libs/1_41_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex). 

Additional usage examples can be found here: [Example for boost shared\_mutex (multiple reads/one write)?](https://stackoverflow.com/questions/989795/example-for-boost-shared-mutex-multiple-reads-one-write)
Well, since a std::map doesn't have a builtin lock, you would have to use a separate lock that protects the map. If the map is all that's protected by that lock you could subclass map to add the lock there along with "lock" and "unlock" calls, but if the lock will be used for other items as well then it's probably not the best idea to do that.

As for "how to correctly synchronize" -- that's very specific to the application at hand. However, for the example given, you have to insert the lock/unlock calls around the read operation as well.

If you have read/write locks, this might also be a good application for one of these.