Reputation: 7357
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
Reputation:
There are a number of advantages;
Upvotes: 15
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