ManagedBuffer Header vs Elements in AllocatedUnfairLock

i was looking at some code that @dmt linked to in another thread recently that provides a re-implementation of the OSAllocatedUnfairLock API. the underlying storage uses a ManagedBuffer to hold the State and lock. i found it somewhat surprising that the State was associated with the buffer's Header and the lock with its Elements rather than being the other way around. anyone have any insights as to why this would be configured in this manner? is the selection arbitrary in this case? is it for storage/access pattern efficiency? something else?

The primary issue for storing it as the element is due to alignment requirements. Since the indirection to the lock pointer needs to be aligned to perform any atomic operation of the contents of that pointer.

1 Like

And a secondary reason is that the raw lock’s address must not change, and the header is exposed as a normal field, which means it’s too easy to accidentally copy it.

1 Like