C ++ 11 how to insert a simple memory barrier?

I want to insert a simple memory barrier, i.e. analogue of C # Thread.MemoryBarrier();. How can I do this in C ++?

This is my code to change:

volatile uint32_t curWriteNum;

void ObtainAndCommit(T* val) {
    memcpy(&storage[curWriteNum & MASK], val, sizeof(T));
     // Ensure storage is written before mask is incremented
     // insert memory barrier
     ++curWriteNum;
}

Update

When I posted this question, I just wanted to learn how to insert a memory barrier. But now we are discussing how to make my program valid, so I am adding a link to the complete list of the class one reader / one writer without memory-lock without locking the ring buffer .

+4
source share
1 answer

The increment must have release semantics, so that the effects of all previous entries will not be reordered after the increment.

curWriteNum std::atomic<int>. std::atomic<int> . , memory_order_seq_cst , , . , curWriteNum.fetch_add(1, std::memory_order_release).

int n = curWriteNum;, , , int n = curWriteNum.load(std::memory_order_acquire);.

. std:: memory_order. , ++ Beyond 2012: Herb Sutter - atomic < > Weapons, 1 of 2.

+4

All Articles