Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safety of c++ maps

This is about thread safety of std::map. Now, simultaneous reads are thread-safe but writes are not. My question is that if I add unique element to the map everytime, will that be thread-safe?

  1. So, for an example, If I have a map like this std:map<int, std::string> myMap and I always add new keys and never modify the existing key-value, will that be thread-safe?

  2. More importantly, will that give me any random run-time behavior?

  3. Is adding new keys also considered modification? If the keys are always different while adding, shouldn't it be thread-safe as it modifies an independent part of the memory?

Thanks Shiv

like image 999
shiv chawla Avatar asked Nov 22 '11 22:11

shiv chawla


People also ask

Are C functions thread-safe?

The standard C printf() and scanf() functions use stdio so they are thread-safe. The standard C printf() function is susceptible to changes in the locale settings if called in a multithreaded program.

Are maps thread-safe C++?

It isn't thread safe, insert from two threads and you can end up in an inconstant state.

What does thread-safe mean C?

Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.

Is ++ thread-safe in C?

++ is not defined as thread-safe. the existence of Interlocked.


2 Answers

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

like image 62
Armen Tsirunyan Avatar answered Sep 29 '22 17:09

Armen Tsirunyan


no, yes, yes. You need to obtain exclusive lock when modifying container (including insertion of new keys), though while there's no modification going on you can, of course, safely read concurrently.

edit: http://www.sgi.com/tech/stl/thread_safety.html might be of interest for you.

like image 39
Michael Krelin - hacker Avatar answered Sep 29 '22 19:09

Michael Krelin - hacker