Lets say I have a pointer to an integer.
volatile int* commonPointer = new int();
And I have multiple threads that dereference that pointer.
int blah = *commonPointer;
But, one thread needs to change that pointer's address:
int* temp = new int();
int* old = commonPointer;
InterlockedExchange(&commonPointer,temp);
delete old;
Now, lets ignore the fact that some threads may be reading the "old" value, and some may be reading the "new" value, that's not an issue in my case.
Can there be a scenario where one thread starts to dereference the pointer, just as the address is deleted, and then gets an exception ?
Or is the dereferencing atomic enough so that won't happen ?
Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.
The dereferencing of a pointer shouldn't be much more than copying an address to a (address)register. Thats all. Dereferencing usually means reading from that address as well. Which may vary in cost depending on cache, locality and such.
I read about * referencing operator and & dereferencing operator; or that referencing means making a pointer point to a variable and dereferencing is accessing the value of the variable that the pointer points to.
Pointer to string in C can point to the starting address of the array that is the first character in the array. Pointers can be dereferenced using the asterisk * operator to identify characters stored at a location.
Nothing in the C++ standard guarantees atomicity in this case.
You must protect the relevant code areas with a mutex: even std::atomic
is not enough since it would only provide atomic access to the pointer but that would not include the dereference operation.
Perhaps, C++11
atomic<shared_ptr<int> >
fit your needs. It prevents old value from disappearing until at least one reference to the value is valid.
atomic<shared_ptr<int> > commonPointer;
// producer:
{
shared_ptr<int> temp(new int);
shared_ptr<int> old= atomic_exchange(&commonPointer, temp);
//...
};// destructor of "old" decrements reference counter for the old value
// reader:
{
shared_ptr<int> current= atomic_load(&commonPointer);
// the referent pointed by current will not be deleted
// until current is alive (not destructed);
}
However, lock free implementation of atomic shared ptr is complicated enough so probably locks or spin locks will be used inside the library implementation (even if the implementation is available on your platform).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With