Skip to content

Commit 7634553

Browse files
mknyszekgopherbot
authored andcommitted
runtime: expand Pinner documentation
This change expands the Pinner documentation based on a few points of feedback. - We need a note that the Pinner has a finalizer. - We need a note that the Pinner is safe to reuse. I also added a note that the zero value is ready to use, and expanded upon the use-cases of a Pinner. Fixes #76431. Change-Id: I312385557e67a815db05def02c1b1d7dcaa9d764 Reviewed-on: https://go-review.googlesource.com/c/go/+/726641 LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Auto-Submit: Michael Knyszek <mknyszek@google.com> Reviewed-by: Michael Pratt <mpratt@google.com>
1 parent b133524 commit 7634553

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/runtime/pinner.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,25 @@ import (
1212

1313
// A Pinner is a set of Go objects each pinned to a fixed location in memory. The
1414
// [Pinner.Pin] method pins one object, while [Pinner.Unpin] unpins all pinned
15-
// objects. See their comments for more information.
15+
// objects.
16+
//
17+
// The purpose of a Pinner is two-fold.
18+
// First, it allows C code to safely use Go pointers that have not been passed
19+
// explicitly to the C code via a cgo call.
20+
// For example, for safely interacting with a pointer stored inside of a struct
21+
// whose pointer is passed to a C function.
22+
// Second, it allows C memory to safely retain that Go pointer even after the
23+
// cgo call returns, provided the object remains pinned.
24+
//
25+
// A Pinner arranges for its objects to be automatically unpinned some time after
26+
// it becomes unreachable, so its referents will not leak. However, this means the
27+
// Pinner itself must be kept alive across a cgo call, or as long as C retains a
28+
// reference to the pinned Go pointers.
29+
//
30+
// Reusing a Pinner is safe, and in fact encouraged, to avoid the cost of
31+
// initializing new Pinners on first use.
32+
//
33+
// The zero value of Pinner is ready to use.
1634
type Pinner struct {
1735
*pinner
1836
}
@@ -26,6 +44,7 @@ type Pinner struct {
2644
// are going to be accessed from C code.
2745
//
2846
// The argument must be a pointer of any type or an [unsafe.Pointer].
47+
//
2948
// It's safe to call Pin on non-Go pointers, in which case Pin will do nothing.
3049
func (p *Pinner) Pin(pointer any) {
3150
if p.pinner == nil {
@@ -63,6 +82,7 @@ func (p *Pinner) Pin(pointer any) {
6382
}
6483

6584
// Unpin unpins all pinned objects of the [Pinner].
85+
// It's safe and encouraged to reuse a Pinner after calling Unpin.
6686
func (p *Pinner) Unpin() {
6787
p.pinner.unpin()
6888

0 commit comments

Comments
 (0)