Galimov Albert
Galimov Albert

Reputation: 7357

atomic_compare_exchange vs mutex

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?

Upvotes: 8

Views: 5304

Answers (2)

user82238
user82238

Reputation:

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

Upvotes: 15

John Vint
John Vint

Reputation: 40266

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.

Upvotes: 7

Related Questions