atomic_compare_exchange vs mutex
-
03-07-2021 - |
سؤال
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;
- it's a lot quicker (on Windows, like 10x or 100x - not so much on Linux, like 10% better)
- it scales MUCH better (although still not enough - only to about 100 logical cores)
- it's MUCH cooler and you seem far more intelligent and capable
- 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
لا تنتمي إلى StackOverflow