Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need syncrhonization in this case?

Tags:

c

linux

gcc

x86-64

I have two threads which share a circular queue. The contents of the queue are unsigned numbers (unsigned long on x86_64). One thread is the producer and the other consumer. The producer only writes to an element of the queue if the value of the element in the queue is 0 and producer always produce a non-zero value, whereas consumer only consumes it when its value is non-zero. Also consumer resets the element to 0 whenever it consumes it, so that producer get to know that consumer has consumed it.

Now what I think is that since with this scheme, there is strict access order of elements in the queue, we don't require using synchronization or atomic variables. Is my assumption correct? Or I'm a missing something here? Keep in mind that x86_64 has a relatively strict consistency memory model and only unrelated loads can be placed before a store. Also it has cache coherency which pro-actively updates the caches. Also I use volatile variables to be sure that compilers don't cache them.

like image 902
pythonic Avatar asked Nov 29 '25 16:11

pythonic


2 Answers

Yes, you need synchronization because the producer and consumer may be trying to read to and/or write from the same location at the same time if the consumer has caught up to the producer or vice versa.

Even if your processor performs atomic operations on the data type that you are using you usually need to explicitly request atomic operations (through an appropriate API) to get the appropriate memory barriers and ensure consistency even when your threads are running on different cores.

like image 122
CB Bailey Avatar answered Dec 02 '25 07:12

CB Bailey


I think you don't need sync or atomic variable.

The two thread one producer and one consumer won't conflict with write the same entry.

Because the two thread can't operate on the same location if your cycle queue implemetion is proper(e.g. one read header variable, one write tag variable.). There is no need restrict the entry structure.

And there seems no need reset entry after you read it. Because you should move your read header, producer thread can know whehter one entry could be written by comparing the read header variable and write tag variable.

May that be helpful for you :)

like image 28
wedgwood Avatar answered Dec 02 '25 07:12

wedgwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!