5YrsLaterDBA 5YrsLaterDBA - 4 months ago 34
C Question

should I synchronize the deque or not

I have a

with pointers inside in a C++ application. I know there are two threads to access it.

Thread1 will add pointers from the back and Thread2 will process and remove pointers from the front.

The Thread2 will wait until
reach certain of amount, saying 10 items, and then start to process it. It will only loop and process 10 items at a time. In the meantime, Thread1 may still keep adding new items into the deque.

I think it will be fine without synchronize the
because Thread1 and Thread2 are accessing different part of the
. It is
. So there is no case that the existing memory of the
will be reallocated.

Am I right? if not, why (I want to know what I am missing)?


I know it will not hurt to ALWAYS synchronize it. But it may hurt the performance or not necessary. I just want it run faster and correctly if possible.


The deque has to keep track of how many elements it has and where those elements are. Adding an element changes that stored data, as does removing an element. Changing that data from two threads without synchronization is a data race, and produces undefined behavior.

In short, you must synchronize those operations.