Question

i have a condition in my code like below

    pthread_spin_lock(&slock);
    if (round_robin_next_ == hp_count() - 1 ) {
      round_robin_next_ = 0;
    } else  {
      round_robin_next_++;
    }
   pthread_spin_unlock(&slock);

i use a spin lock In order to make the above thread safe, and make sure each thread gets the next value of round_robin_next_ compared to the previous one. The round_robin_next_ as you can see is circular, goes up to a certain value and comes back to 0.

My question is can the above made lock free somehow by using gcc intrinsics? or some platform specific instructions? i am on 64 bit Linux using gcc 4.7 and i am fine with a platform specific solution doesn't matter if it can't be ported.

Was it helpful?

Solution

In one sense, yes, you can write the above code without a lock; however, I certainly agree with others in that there is a question of "why do away with the lock?" Optimizing to remove the lock may provide better performance, but is it worth your time and effort to specialize the code to the current requirements. With that said, __sync_bool_compare_and_swap is a sufficient intrinsic to implement nearly any synchronization algorithm. For example:

do {
  old = round_robin_next_;
  if (old == hp_count() - 1) { new = 0; }
  else { new = old + 1; }
} while (!__sync_bool_compare_and_swap(&round_robin_next_, old, new));

The intrinsic atomically evaluates whether the memory location still contains old, and if so, then it stores new into that location. If the location did not still contain old, then false is returned and the update is attempted again.

OTHER TIPS

The answer is yes, since the pthread primitives are built on top of those architecture primitives.

So the question becomes what are you trying to actually achieve?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top