Question about atomic operations and reading

Jun 8, 2016 at 8:33am
I was wondering if I need to use atomic read operations for sensetive data. For example:

- Thread 1: InterlockedExchange(&sensetive_data, sensetive_data + 5)
- Thread 2: InterlockedExchange(&sensetive_data, sensetive_data + 3)
- Thread 3: if(sensetive_data > some_number) do_something();

Would this cause any issues? If it does how should I synchronize access?
Jun 8, 2016 at 2:05pm
1
2
 // InterlockedExchange( &sensetive_data, sensetive_data + 5) ; // avoid
InterlockedExchangeAdd( &sensetive_data, 5 ) ; 


... performs an atomic addition of Value to the value pointed to by Addend. ...
This function generates a full memory barrier (or fence) to ensure that memory operations are completed in order.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms683597(v=vs.85).aspx


Using the standard atomic operations library is both easier and portable.
http://en.cppreference.com/w/cpp/atomic

1
2
3
4
5
6
7
8
9
10
11
#include <atomic>
#include <iostream>

int main()
{
     std::atomic<long> v = 25 ;
    
     v += 5 ;
    
     std::cout << "lock free? " << std::boolalpha << v.is_lock_free() << '\n' ; // true (MSVC)
}

http://rextester.com/PHQJO84060
Jun 8, 2016 at 5:20pm
Thanks for the answer. Upon further research I figured that MSVC guarantees that the read will be fine as long as data is marked as volatile and aligned properly.
Jun 8, 2016 at 6:20pm
volatile is pretty much the worst solution possible, because the meaning of volatile in MSVC is so dramatically different from standard C++. If someone one day compiles that code with another compiler, it will be silently accepted, but it will have undefined behavior at runtime.
Topic archived. No new replies allowed.