Lets suppose following:
I have two processes on Linux / Mac OS.
I have mmap
on shared memory (or in a file).
Then in both processes I have following:
struct Data{
volatile int reload = 0; // using int because is more standard
// more things in the future...
};
void *mmap_memory = mmap(...);
Data *data = static_cast<Data *>(mmap_memory); // suppose size is sufficient and all OK
Then in one of the processes I do:
//...
data->reload = 1;
//...
And in the other I do:
while(...){
do_some_work();
//...
if (data->reload == 1)
do_reload();
}
Will this be thread / inter process safe?
Idea is from here:
https://embeddedartistry.com/blog/2019/03/11/improve-volatile-usage-with-volatile_load-and-volatile_store/
Note:
This can not be safe with std::atomic<>
, since it does not "promise" anything about shared memory. Also constructing/destructing from two different processes is not clear at all.
while(...){...}
loop or equivalent. – Solomastd::atomic_ref
if C++20 is available to you. – Hemicycleatomic_ref
if you also want to more efficient non-atomic access to the same object at times. Given this question, it looks like they should just makereload
andatomic<int>
member ofData
. Possibly init with placement-new to be slightly more efficient thandata->reload.store(0, relaxed)
, or yeah that could be a reason to useatomic_ref
, so you can assign to it cheaply while you know there's only one thread. – Contoatomic<int>
in the shared memory and whether it was safe if the virtual addresses (from the 2 processes) were different. Does it need placement new from both processes for correct object life-times ? And if it does need placement new from 2 processes onto the same object is this ok.std::atomic_ref
seems to make all the above questions moot. – Hemicyclemmap
); I forget what the standard has to say about it. – Contovolatile
andatomic
are both bad as you're not going to find ISO/IEEE-level promises about the behavior of either one relative to shared memory. That's just a gap in the standards as they exist. But if you're looking for reality, thenatomic
works fine and does what you want, whilevolatile
does not. Any reasonable system will support that. Some may document it explicitly, others via their source code, others by "yes, everyone knows that is supposed to work". – Frager