Low-Level Atomic Operations

Hm. ManagedBuffer is perfectly happy to have uninitialized bits of its trailing storage capacity. I suppose it will always destroy its entire Header though. The rule here would be that deinitializing a trivial object more than once is considered an error, and that does seem like a good rule that a sanitizer can implement.

Still, given this part

dispose on a strong reference can't possibly leave the storage in an initialized state, and dispose on an optional strong reference would always just be "swap with nil".

I still don't see what the alternative is. I wouldn't want to introduce C++'s "valid but unspecified" into Swift's memory model if we can help it.

EDIT: Okay, I see it. dispose calls something equivalent to Unmanaged.release in that case and leaves the thing-like-unmanaged reference there.

1 Like

dispose() together with the default value destruction logic allows us to implement whatever scheme we want.

The Standard Library is in full control of Storage; if we need it to contain a strong reference, then we can either choose to make it optional and nil it out in dispose() (this is extremely cheap), or we can let the compiler release it as usual during deinitialization (if that's what we need to do).

If we don't need/want Storage to contain a strong reference, then we can simply do whatever custom logic we need to do in dispose() (e.g., calling posix_mutex_destroy if we decide to model POSIX mutexes this way). We don't even need to mutate the value since value destruction will be a noop in this case.

Having dispose() prepares for all possible scenarios.

Exactly! It's super subtle, but we need it to be able to emulate custom deinits in a class (or rather, a move-only type).

This has been an extremely productive discussion, and as a result, the feature has evolved a great deal over this last month or so -- thank you very much, all of you!

This feature is now in review over in the SE-0282: Low-Level Atomic Operations thread. See you there!

7 Likes

Meta, but I just wanted to remark on how exemplary I think this pitch has been. The proposal document was an excellent write-up of the change, and the discussion in this thread has been really productive (and informative). Kudos, @lorentey!

17 Likes