I am playing with atomic reads and writes currently and have hit a wall in my understanding. I understand that writing to a variable (eg via increment) has to be atomic, but I'm not sure about reading the variable.
Consider _InterlockedExchangeAdd
on Windows, or __sync_add_and_fetch
on Linux. I cannot find a function that atomically retrieves the value being updated. Now I've done my research before posting here and Are C++ Reads and Writes of an int Atomic? tells me that a read isn't atomic.
1) If I use the functions above, how do I atomically read the value, say if returning it from a function?
2) If I didn't want to use these functions and just wanted to lock a mutex before every write of my "atomic" variable, in the function that retrieves the current value of the variable, would I need to first lock the mutex, copy the current value, unlock the mutex then return the copy?
EDIT
I am using a compiler that doesn't have access to the atomic headers, hence have to use these APIs.