Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stl map find thread safe

Is find call on stl map thread safe?

like image 859
Maanu Avatar asked May 06 '11 14:05

Maanu


People also ask

Is map find thread-safe?

Map (ordered or not) doesn't have any global state. The only global thing it accesses is dynamic memory management (new/delete) which is guaranteed to be thread safe by the standard. So, don't worry.

Are std::map thread-safe?

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

Is std :: max thread-safe?

It is inherently thread-safe. There are no data races on concurrent memory reads. However, you must guarantee safe initializations by only a single thread. As Max S.

Is C++ map insert thread-safe?

No, std::map::insert is not thread-safe. There are many reasons why your example may not crash. Your threads may be running in a serial fashion due to the system scheduler, or because they finish very quickly (1000 iterations isn't that much).


1 Answers

No, the C++ spec makes no guarantees on thread safety in the spec for operations on any STL containers. If thread safety is important, the you should provide your own locking.

That being said, different implementations seem to offer different guarantees. Most seem to allow multiple concurrent readers, for example, as long as no writing is being performed concurrently. If you don't care about portability, you can research the documentation for your implementation. For example from here for SGI STL:

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.

From this answer, a similar guarantee seems to be made by Dinkumware (they make Microsoft's STL implementation).

Multiple threads can safely read the same container object. (There are nunprotected mutable subobjects within a container object.)

Two threads can safely manipulate different container objects of the same type. (There are no unprotected shared static objects within a container type.)

You must protect against simultaneous access to a container object if at least one thread is modifying the object. (The obvious synchronization primitives, such as those in the Dinkum Threads Library, will not be subverted by the container object.)

like image 133
Doug T. Avatar answered Oct 05 '22 22:10

Doug T.