Is core.internal.atomic.atomicFetchAdd implementation really lock free?

max haughton maxhaton at gmail.com
Sat Dec 3 20:18:07 UTC 2022


On Saturday, 3 December 2022 at 13:05:44 UTC, claptrap wrote:
> On Saturday, 3 December 2022 at 03:42:01 UTC, max haughton 
> wrote:
>> On Wednesday, 30 November 2022 at 00:35:55 UTC, claptrap wrote:
>>> On Wednesday, 30 November 2022 at 00:16:00 UTC, rikki 
>>> cattermole wrote:
>>>> On 30/11/2022 1:12 PM, H. S. Teoh wrote:
>>>>> Hmm, that's weird that the docs would say that.  I've 
>>>>> always been under
>>>>> the impression that core.atomic ops use locks to achieve 
>>>>> atomicity.
>>>>
>>>> No its correct.
>>>>
>>>> As long as the hardware supports atomic operations, it'll 
>>>> use those instructions. It does have a fallback to use a 
>>>> mutex if need be though, which might be where you got that 
>>>> idea from.
>>>
>>> It really shouldn't do that IMO. People expect atomic ops to 
>>> be lock-free, it should be compile error if it cant be so.
>>
>> I expect atomic ops to provide correct memory consistency, and 
>> preferably be atomic where the platform allows it.
>
> I am really hoping that "preferably atomic" was just a poor 
> choice or words.
>
> I guess regarding the other issues I still think of atomic ops 
> in terms of what the cpu does, so a high level wrapper around 
> them that takes a lock is the complete antithesis to what is 
> actually desired.
>
> I mean the whole point of atomic ops is to be able to avoid 
> using locks.
>
> And if you look at the phobos docs...
>
> "Atomically adds mod to the value referenced by val and returns 
> the value val held previously. This operation is both lock-free 
> and atomic."
>
> https://dlang.org/library/core/atomic/atomic_fetch_add.html

If it provides the same memory ordering guarantees does it matter 
(if we ignore performance for a second)? There are situations 
where you do (for reasons beyond performance) actually need a 
efficient (no overhead) atomic operation in lock-free coding, but 
these are really on the edge of what can be considered guaranteed 
by any specification.

Obviously they *should* be atomic, but not all platforms have 
atomics and not all platforms support the same atomic privileges 
- but they all need to support the same code/patterns. Our 
atomics prefer to error whereas the C++ ones have a fallback 
thing for large types and so on.


More information about the Digitalmars-d mailing list