# ManagedBuffer Header vs Elements in AllocatedUnfairLock

**URL:** <https://forums.swift.org/t/managedbuffer-header-vs-elements-in-allocatedunfairlock/74566>\
**Category:** Using Swift\
**Tags:** question, managedbuffer\
**Created:** [September 13, 2024, 1:05pm UTC](https://forums.swift.org/t/managedbuffer-header-vs-elements-in-allocatedunfairlock/74566 "2024-09-13T13:05:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jamieQ](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jamieq/32/5117_2.png) [@jamieQ](https://forums.swift.org/u/jamieQ)\
**Post date:** [September 13, 2024, 1:05pm UTC](https://forums.swift.org/t/managedbuffer-header-vs-elements-in-allocatedunfairlock/74566/1 "2024-09-13T13:05:14Z")

</div>

i was looking at some code that @dmt linked to in [another thread](https://forums.swift.org/t/parallel-computation-dag-shared-futures/74404/19) recently that provides a re-implementation of the `OSAllocatedUnfairLock` API. the underlying [storage](https://github.com/yandex/vgsl/blob/90d8f14d2b3848c1df62af5e72f73043b8baa814/VGSLFundamentals/concurrency/AllocatedUnfairLock.swift#L11) 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?

---

<div class="post-metadata">

**Author:** ![Philippe\_Hausler](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/philippe_hausler/32/22569_2.png) [@Philippe\_Hausler](https://forums.swift.org/u/Philippe_Hausler)\
**Post date:** [September 13, 2024, 4:20pm UTC](https://forums.swift.org/t/managedbuffer-header-vs-elements-in-allocatedunfairlock/74566/2 "2024-09-13T16:20:15Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [September 13, 2024, 4:31pm UTC](https://forums.swift.org/t/managedbuffer-header-vs-elements-in-allocatedunfairlock/74566/3 "2024-09-13T16:31:32Z")

</div>

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.
