If there is only read-write conflict on an integer, i.e., some threads are reading but only one thread is writing. There's no write-write conflict.
Furthermore, there's no ordering requirements. That is to say, even atomic variables are used, memory_order_relaxed is enough for all reading and writing.
In this case, is atomic variable a must? If I just use a volatile integer, will there be any potential harms?
To give an example, let's say we have a ring buffer, and there are only two threads accessing this ring buffer. One consumer thread (will write to consumer_index, and read from producer_index), and one producer thread (will write to producer_index, and read from consumer_index).
We have to let producer index be atomic, i.e.,
std::atomic<size_t> producer_index;
This is because, when the consumer thread sees the producer_index is advanced, consumer will assume that the content on the ring buffer must be ready to consume (the producer must have pushed the data already). So there's some ordering here.
However, the consumer index is different. When the producer thread sees that the consumer_index is advanced, it doesn't need to know anything about the ring buffer, it can safely re-use that space. The consumer thread must have popped this data and saved to somewhere else and the producer need not to care about where it is saved.
So I don't see the need to make consumer_index as atomic here. Is a volatile enough for this consumer_index?
volatile size_t consumer_index;
I hope I explained the situation clearly. Thanks.