Pinning lifetime (source code)

= Pinning lifetime

The <pinning lifetime> is the interval during which a <pinned memory object> must retain its address for all consumers entitled to use a non-relocatable <pointer> into it. The interval must cover actual memory access, rather than merely the act of handing out the address. Microsoft's `fixed` statement guarantees address stability during its body and restricts its declared pointer to that statement; a pointer retained for later work needs a guarantee covering that later work too.<Fixed statement in the C reference by Microsoft>[Opening definition and array-element/object-field lifetime guarantees]{ref}

For an original timing example, suppose a pin starts at0ms, an external operation receives the address at0.5ms, its submission function returns at1ms, and its final memory access finishes at5ms. Releasing the pin at the function's return leaves4ms of possible access after address stability has ended. Releasing it only after completion at5ms can cover the whole access interval. These times describe an illustrative protocol, not a timing claim about a particular runtime or device.

If the pin is active on $[t_p,t_r)$, every access time $t_a$ must satisfy $t_p\le t_a<t_r$. With several users, the release point must follow the last access by all of them. A count of outstanding operations can enforce this rule: after two operations start, one completion changes the count from2 to1 and does not permit release; the last completion changes1 to0. <Asynchronous pin release> therefore depends on a completion guarantee. Requesting that unfinished work stop does not by itself demonstrate that its final access has ended.

The <pinning lifetime> and data synchronization solve different problems. Stable addresses do not prevent two users from changing the same <bytes> concurrently; a <mutex> or another synchronization mechanism may still be needed. Nor should a pin be held indefinitely just because longer protection seems convenient: pinning can obstruct <memory compaction>, as the <pinned memory object> layout example shows. The useful interval is long enough for the access contract and ends when that contract permits release.