Domanda

I have the following C code:

...
data[index] = something;
a_write_memory_barrier();
index = new_index;
...

The code is not protected by a lock(others just read data and index), I want to make sure data[index] is stored before the updating of index. There are memory writes and reads of other variables around this code, but they do not matter, so GCC can freely reorder them(and I hope it does so for optimization). Just guarantee the order of data[index] and index is enough. How should a_write_memory_barrier() be implemented to achieve this goal?

È stato utile?

Soluzione

If you need to care about out of order execution (you probably work in a distributed framework), that you need to think of load load , store store and full barriers , of course if your architecture supports TSO (total store ordering) than you don't care about store barriers, your write operation will be sequential as written in the code.

If you from the other hand worry about compiler reordering , think of using Volatile (google it)

In your example store barrier will solve your problem , the implementation of such a barrier is dependent on the architecture and a compiler that you use:

e.g.

for sparc and gcc compiler :

   #define MEMBAR_STORESTORE()  asm volatile ("membar #StoreStore":::"memory")
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top