0

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 ?

eswaat
  • 733
  • 1
  • 13
  • 31

1 Answers1

0

You need to use a blocking test. non-blocking tests like a spin lock which at best is test and sleep in a loop take a lot of processor cycles at the detriment to all other processes. Try using a semaphore

phil
  • 561
  • 3
  • 10