MIKU_LINK
MIKU_LINK

Reputation: 192

Mutithreading accessing one std::map , will cause unsafe behavior?

If more than one thread access one map object, but, I can make sure any of these threads accessing will not have the same key, and the accessing is just like:

//find value by key
//if find
// erase the object or change the value
//else
// add new object of the key

Will the operation cause synchronization problem?

Upvotes: 3

Views: 515

Answers (3)

paxdiablo
paxdiablo

Reputation: 881323

Unless the docs (ie, the ISO C++11 standard) say it's thread-safe (and they don't), then that's it. Period. It's not thread-safe.

There may be implementations of a std::map that would allow this but it's by no means portable.

Maps are often built on red-black trees or other auto-balancing data structures so that a modification to the structure (such as inserting or deleting a key) will cause rebalancing.

You should wrap read and write operations on the map with something like a mutex semaphore, to ensure that synchronisation is done correctly.

Upvotes: 1

Tim Ruddick
Tim Ruddick

Reputation: 1403

You will have concurrency problems if any of the threads inserts into the tree. STL map is implemented using a red-black tree (or at least that's what I'm familiar with — I don't know whether the Standard mandates red-black tree). Red-black trees may be rebalanced upon insert, which would lead to all sorts of races between threads.

Read-only access (absolutely no writers) would be fine, but keep in mind operator[] is not read-only; it potentially adds a new element. You'd need to use the find() method, get the iterator, and derefence it yourself.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Yes, doing concurrent updates without proper synchronization may cause crashes, even if your threads access different keys: the std::map is based on trees, trees get rebalanced, so you can cause a write to a parent of a node with a seemingly unrelated key.

Moreover, it is not safe to perform read-only access concurrently with writing, or searching unlocked + locking on write: if you have threads that may update or delete nodes, you must lock out all readers before you write.

Upvotes: 5

Related Questions