Do I need synchronization in this case?

I have two threads that share a circular queue. The contents of the queue are unsigned numbers ( unsigned longon x86_64). One thread is a producer and another consumer. The producer writes only the queue element if the value of the element in the queue is 0, and the producer always produces a non-zero value, while the consumer consumes it only when its value is non-zero. In addition, the consumer resets the item to 0 when he consumes it, so that the manufacturer finds out that the consumer consumes it.

Now I think that since there is a strict access order for the elements in the queue with this scheme, we do not need to use synchronization or atomic variables. Is my assumption correct? Or am I missing something here? Keep in mind that x86_64 has a relatively strict consistency memory model, and only unrelated loads can be placed in front of the repository. In addition, it has cache coherency that actively updates caches. I also use variables volatileto make sure compilers do not cache them.

+3
source share
3 answers

Yes, you need synchronization, because the producer and the consumer can try to read and / or write from the same place at the same time if the consumer has caught up with the manufacturer or vice versa.

, , ( API), , .

+3

, .

.

, (, , ). .

, , reset . , , .

:)

+2

You don't seem to need synchronization if the producer and consumer have access to only one variable. But since you said you were using a circular buffer, you are using an index. An index variable is vulnerable if not synchronized.

0
source

All Articles