Reputation: 10539
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.
Upvotes: 3
Views: 460
Reputation: 1
Will this be thread / inter process safe?
No.
One problematic and common assumption is that volatile is equivalent to “atomic”. This is not the case. All the volatile keyword denotes is that the variable may be modified externally, and thus reads/writes cannot be optimized.
Your code needs atomic access to the value. if (data->reload == 1)
won't work if it reads some partial/intermediate value from data->reload
.
And nevermind what happens if multiple threads do read 1
from data->reload
- your posted code doesn't handle that at all.
Also see Why is volatile not considered useful in multithreaded C or C++ programming?
Upvotes: 5