Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force memory ordering

If there are pointers "A" and "B", with a requirement such that any writes to "A" should be made visible before any writes to "B" are made visible. If I am not allowed to use locks and if I am not allowed to declare these variables as "volatile", will the following code guarantee that, the above requirement will be met?

volatile temp;

*A = value1;
temp = *A;

if (temp == value1) {
    *B = value2
}
like image 814
sAn Avatar asked Aug 02 '26 22:08

sAn


2 Answers

You will want to use memory barriers or fences: see http://en.wikipedia.org/wiki/Memory_barrier

In the Linux kernel you can use the rmb() or wmb() calls.

Under pthreads you can use pthread_barrier_wait(), though that doesn't appear to be in my pthreads manpages.

On MSVC, look at Force order of execution of C statements? - which also has some good general information.

If you find an 'atomic' library, that will normally include barrier functions.

like image 124
abligh Avatar answered Aug 06 '26 04:08

abligh


The answer is simple. You cannot. Reordering can happen because:

  • Compiler will decide to reorder (it is allowed to do so, although this depends on compiler flags, etc);
  • Processor will decide to reorder. If the the processor is complex enough it will definitely do so.

To force memory ordering you need synchronization. Unfortunately there are tons of approaches here. Each approach has its own pros and cons. Depending on your situation you need to pick some.

like image 22
Kirill Kobelev Avatar answered Aug 06 '26 04:08

Kirill Kobelev



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!