Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

multithreading - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...