I want to understand CAS logic, and write my own stack code without pop function. I doubt that my function is whether vulnerable or not.
#define MAX_STACK_ENTRY 256
int stack_entry[MAX_STACK_ENTRY];
int entry_num = 0;
void push(int inp)
{
int last;
__atomic_load(&entry_num, &last, __ATOMIC_RELAXED);
do
{
// because we want to check stack is full, first load entry_num
if(last >= MAX_STACK_ENTRY)
{
printf("stack is full");
return;
}
// check entry_num == last -> this thread success CAS. -> entry_num = last + 1
// check entry_num != last -> another thread success CAS. -> last = entry_num
} while(!__atomic_compare_exchange_n(&entry_num, &last, last+1, 1, __ATOMIC_RELAXED, __ATOMIC_RELAXED));
stack_entry[last] = inp;
}
I think this code is not vulnerable unless there is no pop function. __atomic_compare_exchange_n
doesn't need to get other memory order. ot.
Preventing reordering is not needed, because operations are dependent with each other and executed sequentially.
I think it is not correct, then,
while(!__atomic_compare_exchange_n(&entry_num, &last, last+1, 1, __ATOMIC_ACQUIRE, __ATOMIC_RELEASE));
is needed.
I want to clarity my understand is wrong or not.