Question

I have seen some doc about Linux memory barrier. It mentioned that there are read memory barrier and write memory barrier. It is easy for me to understand the meaning of the write memory barrier, I do not see necessity of the read memory barrier!

Is it just to keep the read order of memory area? if the order is reverse I think the value still should be right, isn't it?

So is the read memory barrier : read operation barrier read operation or write operation barrier read operation?

It confuses me!

Was it helpful?

Solution

A read memory barrier forces reads before it to finish before reads after it. This is useful, for example, with memory mapped I/O, where a read from memory is actually a read from some device connected to the system.

MMIO reads need to be performed in program order because they might have side effects on the device you are reading from. For example, if the device is streaming data, reading the value could cause the device to replace it with a new value. It could also cause an action which may trigger a change at a different MMIO location. Therefore, reads to these two locations must be ordered, since the results depend on the order they are performed.

OTHER TIPS

Even reads that have no side effects have to be ordered sometimes. Consider the following idiom:

extern some_flag_type message_is_ready_flag;
extern some message_type message_data;
while(message_is_ready_flag)     // First read
    continue;
... = message_data;              // Second read

Assume some other thread will write to message_data first, and then writes to message_is_ready_flag.

If in the code above, the second read happens first, it might not read the intended value. Note that the writing thread needs to use a corresponding writer barrier. That's why the Linux documentation notes that "read barriers should normally be paired with write barriers".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top