Asynchronous pin release (source code)

= Asynchronous pin release

<Asynchronous pin release> ends the address-stability guarantee for a <pinned memory object> after an operation that can continue beyond its submission call. Its central condition is that no unfinished consumer may still access the pinned address. Returning from submission is sufficient only when the operation's contract says that all access has ended. Microsoft's asynchronous native-call example stores the pin handle in callback state and disposes it during completion cleanup.<Memory and Span usage guidelines by Microsoft>[Rule10, asynchronous native-call wrapper and completion callback]{ref}

For an original event sequence, suppose an operation acquires a pin at0ms, submits at1ms, returns a pending result at2ms and finishes its last access at8ms. Completion cleanup at8ms can end the <pinning lifetime>; cleanup at2ms cannot. If a request to stop arrives at3ms but the operation acknowledges completion only at6ms, the request alone does not authorize release at3ms. The actual access contract, rather than the desired outcome, determines when the address may change.

An implementation needs a single owner for cleanup across all completion paths. Submission might fail before any callback is promised, complete immediately, or complete later. Each path must transfer or retain the cleanup responsibility consistently. The <exactly-once pin cleanup> requirement avoids both leaking a pin and releasing the same handle twice. The primary Microsoft example explicitly cleans up an exception before a callback can be invoked, and funnels immediate and deferred completion through a completion routine.<Memory and Span usage guidelines by Microsoft>[Rule10, exception cleanup and non-pending completion branch]{ref}

With overlapping users, releasing one operation's interest does not establish that every user has finished. A <reference counting> protocol can track outstanding access leases, provided starting new work and deciding that the last lease ended are synchronized. An observed zero count without protection against a simultaneous new user is not sufficient. A <mutex> or another appropriate synchronization mechanism can protect that transition.

The completion signal must itself describe the end of access. Microsoft's task-based buffer rule forbids a consumer from continuing to use the memory after the returned task reaches a terminal state.<Memory and Span usage guidelines by Microsoft>[Rule4, consumer lifetime and task terminal state]{ref} An API that reports cancellation before its underlying user has stopped requires another completion guarantee before pin cleanup. Retaining the pin protects the address; it does not by itself prevent concurrent data races or determine who may reuse the buffer.