Skip to content

Commit 3d6d4e9

Browse files
authored
Merge pull request #1668 from ydb-platform/xruntime
Added package internal/xruntime with helper function AddCleanup
2 parents 4b7a7de + 5911b50 commit 3d6d4e9

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

internal/xruntime/cleanup.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//go:build !go1.24
2+
3+
package xruntime
4+
5+
import "runtime"
6+
7+
func AddCleanup[T, S any](ptr *T, cleanup func(S), arg S) {
8+
runtime.SetFinalizer(ptr, func(ptr *T) {
9+
cleanup(arg)
10+
})
11+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
//go:build go1.24
2+
3+
package xruntime
4+
5+
import "runtime"
6+
7+
func AddCleanup[T, S any](ptr *T, cleanup func(S), arg S) {
8+
runtime.AddCleanup(ptr, cleanup, arg)
9+
}

internal/xruntime/cleanup_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package xruntime
2+
3+
import (
4+
"runtime"
5+
"testing"
6+
"time"
7+
)
8+
9+
func TestAddCleanup(t *testing.T) {
10+
cleanupCalled := make(chan struct{})
11+
func() {
12+
v := &struct {
13+
a int64
14+
b string
15+
c bool
16+
}{}
17+
AddCleanup(v, func(cleanupCalled chan struct{}) {
18+
close(cleanupCalled)
19+
}, cleanupCalled)
20+
}()
21+
runtime.GC()
22+
select {
23+
case <-cleanupCalled:
24+
case <-time.After(time.Second):
25+
t.Fail()
26+
}
27+
}

0 commit comments

Comments
 (0)