VC. STL Newsgroup Good Questions (5)
Article last modified on 2002-5-30
----------------------------------------------------------------
The information in this article applies:
-Microsoft Visual C ++, 32-bit Editions, version 6.0, SP5
----------------------------------------------------------------
Are Containers Thread Safe?
Question:
Does STL containers have thread security? Or do I need to provide protection when multiple threads access data? I think it should have thread security, but I want to confirm it. |
Answer:
In all mainstream STL Implementation Solutions, almost all containers are thread-safe: 1) when one thread reads and writes to one instance, the other thread can read and write to another instance. 2) Multiple Threads can read the same iner at the same time. 3) when multiple threads write the same iner, you should be responsible for arranging mutually exclusive operations. A special case is std: string. Some STL implementation vendors (including MS VC6) Use strings with reference counts! This means that two std: string instances may share the same underlying data. This causes the first rule to be broken! Take a look at this Code: String s1 = "abcd "; String s2 = s1; In the implementation version of the reference count, these words mean: first allocate a piece of memory to "abcd", a number of reference counts; both s1 and s2 will reference this piece of memory, the reference count is 2. The reference count is intended to optimize the copy behavior when strings is transferred out of functions. However, this algorithm is NOT thread-safe! If you pass s2 to another thread, two threads may attempt to modify the same memory! There will be unpredictable behavior. In theory, you can add thread synchronization between two threads, but the cost of this synchronization will be greater than the benefit you get from the reference count! This is why mainstream STL vendors no longer use reference counting. For example, Dinkumware STL shipped with VC7. |
(To be Continued)
Written by zhengyun@tomosoft.com
Trackback: http://tb.blog.csdn.net/TrackBack.aspx? PostId = 12677