I am new to std::atomic in c++ and trying to understand the implementation of compare and exchange operations under ARM processors.I am using gcc on linux.
When i look into the assembly code
mcr p15, 0, r0, c7, c10, 5
.L41:
ldrexb r3, [r2]
cmp r3, r1
bne .L42
strexb ip, r0, [r2]
cmp ip, #0
bne .L41
.L42:
mcr p15, 0, r0, c7, c10, 5
My understanding is
- it takes multiple instructions to do compare and exchange.
- ldrex marks the memory location as exclusive and reads the data.
- strex stores the data and clears the exclusive flag for that location.
My questions are
does ldrex mark the Virtual addr. as exclusive or the physical address?
If Process P1 marks the virtual address as exclusive and a process switch occurs to P2, will that virtual addr. be accessible in P2? what will happen if P2 also execute an ldrex on the same address.
If Process P1 marks the physical address as exclusive and a process switch occurs, when P1 resumes isn't there a chance that the data now resides in a different location in physical memory due to paging.
I am trying to understand this because, i want to do a compare and exchange on a shared memory location accessed by multiple processes.
My c++ function looks like
std::atomic<bool> *flag;
flag = (std::atomic<bool> *) (shm_ptr);
bool temp = false ;
while(!std::atomic_compare_exchange_strong((flag),&temp,true))
{
std::this_thread::yield();
}
// update shared memory
std::atomic_store((flag), false);
std::atomic_store((flag), false);
be atomic? The flag is 'true' after lock is taken. It is not needed to be released atomically, due to other threads never could executestd::atomic_compare_exchange_strong()
successfully until 'false' value is written back. – user3124812