sync: use runtime.AddCleanup instead of runtime.SetFinalizer

This changes the use of finalizers to the cleanup implementation in
tests.

Updates #70907

Change-Id: I7d7289999a83fa53f538698f34294f7d9651c921
Reviewed-on: https://go-review.googlesource.com/c/go/+/640735
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Carlos Amedee 2025-01-06 12:59:07 -05:00
parent c8545439b5
commit 954e2c0b06
3 changed files with 9 additions and 15 deletions

View File

@ -225,15 +225,13 @@ func TestIssue40999(t *testing.T) {
// add an initial entry to bias len(m.dirty) above the miss count. // add an initial entry to bias len(m.dirty) above the miss count.
m.Store(nil, struct{}{}) m.Store(nil, struct{}{})
var finalized uint32 var cleanedUp uint32
// Set finalizers that count for collected keys. A non-zero count // Add cleanups that count for collected keys. A non-zero count
// indicates that keys have not been leaked. // indicates that keys have not been leaked.
for atomic.LoadUint32(&finalized) == 0 { for atomic.LoadUint32(&cleanedUp) == 0 {
p := new(int) p := new(int)
runtime.SetFinalizer(p, func(*int) { runtime.AddCleanup(p, func(c *uint32) { atomic.AddUint32(c, 1) }, &cleanedUp)
atomic.AddUint32(&finalized, 1)
})
m.Store(p, struct{}{}) m.Store(p, struct{}{})
m.Delete(p) m.Delete(p)
runtime.GC() runtime.GC()

View File

@ -203,9 +203,7 @@ func TestOnceXGC(t *testing.T) {
t.Run(n, func(t *testing.T) { t.Run(n, func(t *testing.T) {
buf := make([]byte, 1024) buf := make([]byte, 1024)
var gc atomic.Bool var gc atomic.Bool
runtime.SetFinalizer(&buf[0], func(_ *byte) { runtime.AddCleanup(&buf[0], func(g *atomic.Bool) { g.Store(true) }, &gc)
gc.Store(true)
})
f := fn(buf) f := fn(buf)
gcwaitfin() gcwaitfin()
if gc.Load() != false { if gc.Load() != false {

View File

@ -109,12 +109,10 @@ loop:
if try == 1 && testing.Short() { if try == 1 && testing.Short() {
break break
} }
var fin, fin1 uint32 var cln, cln1 uint32
for i := 0; i < N; i++ { for i := 0; i < N; i++ {
v := new(string) v := new(string)
runtime.SetFinalizer(v, func(vv *string) { runtime.AddCleanup(v, func(f *uint32) { atomic.AddUint32(f, 1) }, &cln)
atomic.AddUint32(&fin, 1)
})
p.Put(v) p.Put(v)
} }
if drain { if drain {
@ -126,11 +124,11 @@ loop:
runtime.GC() runtime.GC()
time.Sleep(time.Duration(i*100+10) * time.Millisecond) time.Sleep(time.Duration(i*100+10) * time.Millisecond)
// 1 pointer can remain on stack or elsewhere // 1 pointer can remain on stack or elsewhere
if fin1 = atomic.LoadUint32(&fin); fin1 >= N-1 { if cln1 = atomic.LoadUint32(&cln); cln1 >= N-1 {
continue loop continue loop
} }
} }
t.Fatalf("only %v out of %v resources are finalized on try %v", fin1, N, try) t.Fatalf("only %v out of %v resources are cleaned up on try %v", cln1, N, try)
} }
} }