1 year ago
#371170
John
Could reading & writing int which is declared with volatile and stored on a aligned address be garanteed to be atomic?
Here the related code snippet:
#include <functional>
#include <thread>
#include <iostream>
#include <chrono>
#include <atomic>
#ifdef NO_STUCK_WITH_OPTIMIZATION
using TYPE = std::atomic<int>;
#else
using TYPE = volatile int; //The progrom seems not get stuck if the optimization is enabled.
#endif
int main()
{
TYPE is_run{1}; //If the is_run is declared as volatile, then the program would never get stuck?
auto thread = std::thread([&is_run](){while(1==is_run){
}
std::cout << "thread game over" << std::endl;
});
is_run = 0;
thread.join();
}
Question: Could reading & writing int which is declared with volatile
and stored on a aligned address be garanteed to be atomic? Or the conclusion is right just on X86 platform?
Somebody told me not to use volatile
. This keyword was added before C++ had a memory model. It will make some issues go away (by preventing some compiler optimization), but not all and your code would still have UB.
And somebody told me that it's atomic on any platform.
I found some posts on SO, but the posts were updated more than 10 years ago. For example:
ARM: Is writing/reading from int atomic?. [^1]
Are C++ Reads and Writes of an int Atomic?. [^2]
UPDATED: And as per (this post)[https://codywu2010.wordpress.com/2014/11/03/is-int-write-operation-atomic-on-x86_64/] [^3], which says that:
Nearly always we read from documents and web posts that X86_64 can do 64bits write operation atomically. So if thread 1 is writing value A to an integer while thread 2 is writing value B to the same integer we are guaranteed to observe either value A or value B and never anything in between, ignoring initial value of course.
It seems that the posts (marked with [^1] [^2] [^3]) all says that it's atomic.
And now I am really confused now.Could somebody shed some light on this matter?
c++
data-race
0 Answers
Your Answer