]> Cypherpunks repositories - gostls13.git/commitdiff
weak: test the use of runtime.AddCleanup
authorCarlos Amedee <carlos@golang.org>
Fri, 14 Feb 2025 18:01:02 +0000 (13:01 -0500)
committerCarlos Amedee <carlos@golang.org>
Tue, 25 Feb 2025 16:44:32 +0000 (08:44 -0800)
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 <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
src/weak/pointer_test.go

index d2ee6512440dd7188f8b7ef79ae9f695cd253c0e..da464a8d01f2d010b8d97d52e58729f113e7d71b 100644 (file)
@@ -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)