Search code examples
c++multithreadingmutexatomiclock-free

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?


Solution

  • 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.