Oh, my GoD! Goroutines on D
Brad Roberts
braddr at puremagic.com
Fri Jan 3 22:24:40 UTC 2025
On 1/2/2025 4:17 PM, Guillaume Piolat via Digitalmars-d wrote:
> On Thursday, 2 January 2025 at 19:59:26 UTC, Jin wrote:
>> If someone can tell me what could be wrong here, I would be very
>> grateful.
>
> https://github.com/nin-jin/go.d/blob/master/source/jin/go/queue.d#L67
>
> A concurrent `put` and `popFront` will do nothing to avoid races in
> `Queue`.
> Individual access to _offset is atomic but its point of use in both put
> and popFront is not.
>
> Both functions look like this:
>
> 1. Atomic-read-offset
> 2. Anything can happen
> 3. Atomic-write-offset
>
> If one function has completed 1) then other has completed 1+2+3 then you
> get a race.
> Chaining two atomic things doesn't make the whole atomic, rather classic
> mistake with mutual exclusion.
Probably the most common atomicity error, is atomic check followed by
non atomic acting based on that check. The problem that is overlooked
in that scenario is that while the check itself is safe, by the time the
action proceeds the condition can change. The only safe way is to
combine the check and action into a single atomic transaction.
The next most common is probably the ABA issue. Assuming that because
you see A in the second case, that what you're seeing is still the first
A and that implies that B couldn't and didn't happen.
The lesson here is that you're far better off NOT being clever and
trying to avoid longer lived locks unless you can demonstrate that it's
particularly important and detrimental to the app performance. It's
super easy to get separate/tiny atomic operations wrong and be very hard
to detect/debug that than to get it right at a slightly higher cost with
multi-instruction simple locking.
Not to mention that cpu and os designers have invested energy improving
the performance of mutex and spinlock style code.
There's a time an place for cleverness, but not at the expense of
correctness.
My 2 cents,
Brad
More information about the Digitalmars-d
mailing list