Atomic_compare_exchange vs mutex

What is the point of replacing a mutex lock with a 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));
} 

I can’t understand what benefit we can get by replacing the mutex with this atomic excange?

+5
source share
2 answers

This is usually faster than a mutex. However, you cannot just replace all mutexes with CAS. One CAS will replace one link with another in a safe manner among many threads.

If you have a compound function in which one record depends on the other read (for example), you will need a mutex to ensure atomicity.

+6
source

There are a number of benefits:

  • it is much faster (on Windows, for example 10x or 100x - not so much on Linux, but 10% better).
  • MUCH ( - 100 )
  • , .
  • , , , . , Windows (DISPATCH_LEVEL) Linux ..
+11

All Articles