I am wondering if anyone has run into the following problem----by the way, it is an assumption on my part that this problem exists! I believe it does, given what I know about the STL library, but I have not yet followed a debug trace to confirm an instance of it. I am worried about it, however, given that the STL and in particular, the STL vector is widely used.
The problem I see is this : if an STL vector is full and the user pushes a new element onto it, automated resizing will start. My understanding of what happens is that (a) a new, larger block of memory is allocated to hold the vector's contents, (b) the existing contents of the vector, plus the new element just 'pushed', are copied to that new location, and (here is the important part), (c) the old block of memory previously used by the vector is "freed". I put "freed" in parentheses because I am not sure if STL actually returns the memory to the outer program's memory manager, or keeps it on a list of memory available for STL's reuse. But, either way, the old block of memory is made available for new content.
So, what if we multi-threaded a body of code that had, as a shared variable, an STL vector object. Let's say there is a line of code that does a "push" onto the vector. We can insert a "critical section" pragma for this line. But, I don't believe this protects other threads that might be reading the content of the vector at the same (or psuedo-same) time that the push is being done. If the push triggers automated resizing of the vector, it seems to me there is a finite chance that another thread might read corrupted data. For instance, what if the following happens: thread A launches a read from the vector, but the data is not in cache and the processor executing thread A schedules a memory fetch, but, before this fetch goes out (meaning, the memory address has been sent to the processor's bus interface unit, but it's sitting queued there), thread B is doing a critical section push (onto the vector) and the entire process of copying the vector's contents and "freeing" the old block of memory completes, and, then---all of this happening before thread A's processor gets access to the memory bus----another thread, thread C, causes something to be written to the old memory address. For instance, thread C could be creating a new STL vector, a private variable for that thread, and STL might be letting it reuse the memory that was freed. Then, when thread A's processor completes its memory fetch, it will get corrupted data.
This scenario seems possible. I can imagine ways around it---for instance, make all the code that reads from the vector be critical sections just like the push. But, that would be incompatible with good performance.
So, what has others' experience been? Have you thought about this problem, or experienced it? Have you implemented a solution?