1
0
mirror of https://github.com/golang/go synced 2024-11-24 23:07:56 -07:00
Change-Id: I25be338b3519b1658f13d055b579a0aa2d3a35f8
This commit is contained in:
Mateusz Poliwczak 2024-07-29 20:52:06 +02:00
parent 37646b6bbd
commit 7e202ad83f
2 changed files with 22 additions and 4 deletions

View File

@ -48,8 +48,8 @@ func OnceValue[T any](f func() T) func() T {
result T
)
g := func() {
f = nil // Do not keep f alive after invoking it.
defer func() {
f = nil // Do not keep f alive after invoking it.
p = recover()
if !valid {
panic(p)
@ -80,8 +80,8 @@ func OnceValues[T1, T2 any](f func() (T1, T2)) func() (T1, T2) {
r2 T2
)
g := func() {
f = nil // Do not keep f alive after invoking it.
defer func() {
f = nil // Do not keep f alive after invoking it.
p = recover()
if !valid {
panic(p)

View File

@ -198,6 +198,18 @@ func TestOnceXGC(t *testing.T) {
f := sync.OnceValues(func() (any, any) { buf[0] = 1; return nil, nil })
return func() { f() }
},
"OnceFunc panic": func(buf []byte) func() {
return sync.OnceFunc(func() { buf[0] = 1; panic("test panic") })
},
"OnceValue panic": func(buf []byte) func() {
f := sync.OnceValue(func() any { buf[0] = 1; panic("test panic") })
return func() { f() }
},
"OnceValues panic": func(buf []byte) func() {
f := sync.OnceValues(func() (any, any) { buf[0] = 1; panic("test panic") })
return func() { f() }
},
}
for n, fn := range fns {
t.Run(n, func(t *testing.T) {
@ -211,14 +223,20 @@ func TestOnceXGC(t *testing.T) {
if gc.Load() != false {
t.Fatal("wrapped function garbage collected too early")
}
func() {
defer func() { recover() }()
f()
}()
gcwaitfin()
if gc.Load() != true {
// Even if f is still alive, the function passed to Once(Func|Value|Values)
// is not kept alive after the first call to f.
t.Fatal("wrapped function should be garbage collected, but still live")
}
func() {
defer func() { recover() }()
f()
}()
})
}
}