Below is my use case
I have one global variable and multiple thread across all CPU are accessing this.
With atomic compare and exchange
auto old = global_var;
auto new_var = old
for (;;) {
new++;
bool got_it = atomic_compare_and_swap(global_var,
old,
new_var);
if (got_it) {
return new_var;
}
old = global_var;
new_var = old;
}
With spin trylock
for(;;)
{
auto temp = go_for_work();
if (temp -> spin.trylock() == 0 )
{
continue;
}
}
... go_for_work
{
auto old = global_var;
auto new_var = old
new_var++;
global_var = new_var;
return new_var
}
This is rough code I hope it is clear. Let me know if it is not clear.
global_var is not a int it is structure.
So, my main aim is to protect global_var, which one is faster atomic_compare_and_swap or spin.trylock(), also if some other technique ?