0

std::memory_order_acquire barrier guarantees that all the operations such as read/write which goes after the barrier will be performed after all the reading(load) operations before the barrier.

For example, i have a following code:

#include <iostream>
#include <atomic>

int num = 25;

int getValue()
{
    return num;
}

void setValue(int value)
{
    num = value;
}

int main()
{
    std::atomic<int> n;
    int data = getValue();
    n.store(data, std::memory_order_acquire);
    setValue(100);
    std::cout << getValue();
}

Can i be sure that code int data = getValue(); guaranteed will be performed before following code?

n.store(data, std::memory_order_acquire); 
setValue(100); 
std::cout << getValue();

At the atomic storing moment, int data = getValue() guaranteed be performed. I am right?

Dark Rider
  • 9
  • 1
  • 3
  • 1
    Your usage of the barrier is wrong because the context is wrong. What you're asking is guaranteed, not because of the barrier, but because you're not using multithreading in the first place! You should have TWO barriers that run in two threads. – The Quantum Physicist Mar 01 '17 at 08:30
  • Look here: http://stackoverflow.com/questions/13632344/understanding-c11-memory-fences – The Quantum Physicist Mar 01 '17 at 08:32
  • 1
    On top of the previous remark, your definition of the barrier is incorrect, I dont know where you got it . the memory_order_acquire prevent following expression to be moved 'up'. so it affect only `setValue(100);`, `std::cout << getValue();` – UmNyobe Mar 01 '17 at 08:33
  • 1
    You want `std::memory_order_release` for that. – n. m. could be an AI Mar 01 '17 at 08:34
  • @DarkRider: This is the second time you ask the same question in the wrong context. I really, really recommend that you get a good C++ multithreading book and start reading, and I wanna say this in the nicest way possible. You'll never understand complicated concepts, such as atomicity in multithreading, by just asking such questions on Stackoverflow. This is a good book whose PDF you can find online: https://www.amazon.com/C-Concurrency-Action-Practical-Multithreading/dp/1933988770 – The Quantum Physicist Mar 01 '17 at 08:37
  • Strongly suggest that you take 3 hours to watch these 2 presentations. Very watchable and you will learn everything you need to know about concurrency: https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-1-of-2 – Richard Hodges Mar 01 '17 at 08:50

0 Answers0