5YrsLaterDBA 5YrsLaterDBA - 1 month ago 5
C Question

should I synchronize the deque or not

I have a

deque
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
deque
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
deque
because Thread1 and Thread2 are accessing different part of the
deque
. It is
deque
not
vector
. So there is no case that the existing memory of the
container
will be reallocated.

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

EDIT:

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.

Answer

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.