سؤال

What is the point in replacing a mutex lock with block like this

void stack_push(stack* s, node* n)
{
    node* head;
    do
    {
        head = s->head;
        n->next = head;
    }
    while ( ! atomic_compare_exchange(s->head, head, n));
} 

Can't understand what benefit we can get by replacing mutex with this atomic excange?

هل كانت مفيدة؟

المحلول

It is typically faster than a mutex. That being said, you cannot just simply replace all mutexes with a CAS. A single CAS will swap one reference with another safely among many threads.

If you have a compound function in which one write depends on another read (for example), you would need a mutex to ensure atomicity.

نصائح أخرى

There are a number of advantages;

  1. it's a lot quicker (on Windows, like 10x or 100x - not so much on Linux, like 10% better)
  2. it scales MUCH better (although still not enough - only to about 100 logical cores)
  3. it's MUCH cooler and you seem far more intelligent and capable
  4. where no waits or sleeps are required, this code can be used in places where waits or sleeps are forbidden, e.g. interrupt handlers, certain parts of the Windows (DISPATCH_LEVEL) and Linux kernels, etc
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top