From 2f036e1475f9d794451927d90c07d9f8c258db77 Mon Sep 17 00:00:00 2001 From: Carlos Amedee Date: Fri, 14 Feb 2025 13:01:02 -0500 Subject: [PATCH] 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 Reviewed-by: Michael Knyszek --- src/weak/pointer_test.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/weak/pointer_test.go b/src/weak/pointer_test.go index d2ee651244..da464a8d01 100644 --- a/src/weak/pointer_test.go +++ b/src/weak/pointer_test.go @@ -158,6 +158,42 @@ func TestPointerFinalizer(t *testing.T) { } } +func TestPointerCleanup(t *testing.T) { + bt := new(T) + wt := weak.Make(bt) + done := make(chan struct{}, 1) + runtime.AddCleanup(bt, func(_ bool) { + if wt.Value() != nil { + t.Errorf("weak pointer did not go nil before cleanup was executed") + } + done <- struct{}{} + }, true) + + // Make sure the weak pointer stays around while bt is live. + runtime.GC() + if wt.Value() == nil { + t.Errorf("weak pointer went nil too soon") + } + runtime.KeepAlive(bt) + + // bt is no longer referenced. + // + // Run one cycle to queue the cleanup. + runtime.GC() + if wt.Value() != nil { + t.Errorf("weak pointer did not go nil when cleanup was enqueued") + } + + // Wait for the cleanup to run. + <-done + + // The weak pointer should still be nil after the cleanup runs. + runtime.GC() + if wt.Value() != nil { + t.Errorf("weak pointer is non-nil even after cleanup: %v", wt) + } +} + func TestPointerSize(t *testing.T) { var p weak.Pointer[T] size := unsafe.Sizeof(p) -- 2.51.0