C++ Thread-Safe Map

Creating a standard map that is thread safe

You can use a shared_mutex beside your map to acquire shared or unique access. Generally, a write operation will require unique access, while read operations will require shared access.

Any number of threads can acquire shared access, as long as no threads are holding unique access. If a thread attempts to acquire unique access, it waits until all shared access is released.

The standard library and Boost provide shared_lock<T> and unique_lock<T> for scope-bounded acquisition of a shared_mutex.

Beware that some people claim shared_mutex performs poorly, though I haven't seen any evidence or strong analysis to support these claims. It may be worth looking into, if it matters to you.

C++ Thread-Safe Map

Does not meet the criteria that you have specified, but you could have a look at the TBB containers. There is so called concurrent_hash_map which allows multiple threads to access concurrently the data in the map. There are some details, but everything is nicely documented and can give you an idea of the "concurrent container". Depending on your needs this might be totally inappropriate...

C++ thread safety - map reading

If you are talking about the standard std::map and no thread writes to it, no synchronization is required. Concurrent reads without writes are fine.

If however at least one thread performs writes on the map, you will indeed need some sort of protection like a mutex.

Be aware that std::map::operator[] counts as write, so use std::map::at (or std::map::find if the key may not exist in the map) instead. You can make the compiler protect you from accidental writes by only referring to the shared map via const map&.


Was clarified to be the case in the OP. For completeness' sake: Note that other classes may have mutable members. For those, even access through const& may introduce a race. If in doubt, check the documentation or use something else for parallel programming.

What operations are thread-safe on std::map?

In theory no STL containers are threadsafe. In practice reading is safe if the container is not being concurrently modified. ie the standard makes no specifications about threads. The next version of the standard will and IIUC it will then guarantee safe readonly behaviour.

If you are really concerned, use a sorted array with binary search.

Thread-safety of c++ maps

1) Of course not

2) Yes, I hope you'll encounter it during testing, not later

3) Yes, it is. The new element is added in a different location, but many pointers are modified during that.

The map is implemented by some sort of tree in most if not all implementations. Inserting a new element in a tree modifies it by rearranging nodes by means of resetting pointers to point to different nodes. So it is not thread safe



Related Topics



Leave a reply



Submit