Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety of C++ std Containers

I read a lot of posts here with the question if the standard containers for C++ (like "list" or "map" are thread safe and all of them said that it is not in general. Parallel reads should be OK, but parallel writes or parallel reads and writes may cause problems.

Now I found out that at www.cplusplus.com that accessing or modifying the list during most of the operations is safe.

Some examples:

map::find

The container is accessed (neither the const nor the non-const versions modify the container). No mapped values are accessed: concurrently accessing or modifying elements is safe.

map::insert

The container is modified. Concurrently accessing existing elements is safe, although iterating ranges in the container is not.

Do I missunderstand cplusplus.com or is there anything else what I have to know about thread safety in std containers.

Thanks in advance!

PS: I'm asking for C++03 and not for C++11

like image 413
mrwerner Avatar asked Sep 06 '13 11:09

mrwerner


1 Answers

Parallel reads should be OK, but parallel writes or parallel reads and writes may cause problems.

That's correct. That is the guarantee offered in general for unsynchronised access to objects in C++. Such "problems" are formally called data races.

Now I found out that at www.cplusplus.com that accessing or modifying the list during most of the operations is safe.

No, containers don't offer more than the basic guarantee for concurrent reads. There will be a data race if one thread accesses it while another modifies it. However, with some containers, it's sometimes safe to access elements of the container while the container itself is modified.

The first example is saying that find does not modify the container or access element values (only keys), so is safe if other threads are accessing it, or modifying (different) values without modifying the container itself.

The second example is saying that you can safely access an existing element (using a reference or iterator to that element), since inserting an element will not interfere with the existing ones.

I'm asking for C++ and not for C++11

These days, C++ is C++11. If you're asking about historic versions of the language, they had nothing to say about threads, so the question is not answerable in general, only for a specific implementation and thread framework.

like image 62
Mike Seymour Avatar answered Sep 29 '22 03:09

Mike Seymour