question about STL thread-safe and STL debugging
I have two questions about STL
1) why STL is not thread-safe开发者_运维百科? Is there any structure that is thread-safe?
2) How to debug STL using GDB? In GDB, how can I print a vector?
- Container data structures almost always require synchronization (e.g. a mutex) to prevent race conditions. Since threading is not support by the C++ standard (pre C++0x), these could not be added to the STL. Also, synchronization is very expensive for cases where it is not needed. STL containers may be used in multi-threaded applications as long as you perform this synchronization manually. Alternatively, you may create your own thread-safe containers that are compatible with STL algorithms like this thread-safe circular queue.
- A
vector
contains a contiguous block of memory. So, it can be displayed in the same way as a regular array once you find the pointer to this memory block. The exact details depend on the STL implementation you use.
The standard c++ containers are not thread safe because you most likely actually want higher level locking than just the containers themselves. In other words you are likely to want two or more operations to be safe together.
For example, if you have multiple threads running:
v.push_back(0);
v.push_back(1);
You wont get a nice vector of alternating 0's and 1's, they could be jumbled. You would need to lock around both commands to get what you want.
STL is not thread-safe because a lot of people don't need thread safety, and because that introduces threading context into classes that otherwise have no need to know anything about the concept of threads.
You can encapsulate access to containers and provide your own thread safety (or other restrictions imposed by your specific design and implementation.)
- Because there are still single-threaded programs.
- Take a look here.
精彩评论