Thread safety of C++ std Containers

前端 未结 4 777
滥情空心
滥情空心 2020-12-11 01:48

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. Par

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 02:33

    As Marcin pointed out, C++03 doesn't have a notion of thread; hence, you can't assume any thread-safe operation even for concurrent reading in two threads after a write that is completely complete.

    Think about this case: At t=0, you create a thread, let's call A At t=10 sec, thread B (which exists before thread A gets created) writes to a container. At t=1 hour, thread A and B both try to read the container without any synchronization through a 3rd party library (e.g. pthread).

    C++03 only guarantees that thread B will see the correct value. But there is no guarantee that thread A will see the correct value because C++03 expects every program is single thread, and so C++03 specification can only guarantee the sequence of events being visible in the programmed order (as if in 1 thread).

提交回复
热议问题