Skip to content

Commit 2f036e1

Browse files
committed
weak: test the use of runtime.AddCleanup
This change adds a test case for runtime.AddCleanup. Updates #70907 Change-Id: I29cba9dc5b40cec8e610215974e61ee47e10d00f Reviewed-on: https://go-review.googlesource.com/c/go/+/649459 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Michael Knyszek <[email protected]>
1 parent c2ae5c7 commit 2f036e1

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/weak/pointer_test.go

+36
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,42 @@ func TestPointerFinalizer(t *testing.T) {
158158
}
159159
}
160160

161+
func TestPointerCleanup(t *testing.T) {
162+
bt := new(T)
163+
wt := weak.Make(bt)
164+
done := make(chan struct{}, 1)
165+
runtime.AddCleanup(bt, func(_ bool) {
166+
if wt.Value() != nil {
167+
t.Errorf("weak pointer did not go nil before cleanup was executed")
168+
}
169+
done <- struct{}{}
170+
}, true)
171+
172+
// Make sure the weak pointer stays around while bt is live.
173+
runtime.GC()
174+
if wt.Value() == nil {
175+
t.Errorf("weak pointer went nil too soon")
176+
}
177+
runtime.KeepAlive(bt)
178+
179+
// bt is no longer referenced.
180+
//
181+
// Run one cycle to queue the cleanup.
182+
runtime.GC()
183+
if wt.Value() != nil {
184+
t.Errorf("weak pointer did not go nil when cleanup was enqueued")
185+
}
186+
187+
// Wait for the cleanup to run.
188+
<-done
189+
190+
// The weak pointer should still be nil after the cleanup runs.
191+
runtime.GC()
192+
if wt.Value() != nil {
193+
t.Errorf("weak pointer is non-nil even after cleanup: %v", wt)
194+
}
195+
}
196+
161197
func TestPointerSize(t *testing.T) {
162198
var p weak.Pointer[T]
163199
size := unsafe.Sizeof(p)

0 commit comments

Comments
 (0)