Skip to content

Commit 4524009

Browse files
streamdpcherrymui
authored andcommitted
[release-branch.go1.24] runtime: Added usage example for the runtime.AddCleanup() function.
The existing description of the function lacks usage examples, which makes it difficult to understand, so I added one. There is no open issue about this, since the implementation seems trivial. For #72795 Fixes #72796 Change-Id: I96b29f0b21d1c7fda04128239633c8a2fc36fef2 Reviewed-on: https://go-review.googlesource.com/c/go/+/649995 Reviewed-by: Carlos Amedee <carlos@golang.org> Reviewed-by: Michael Knyszek <mknyszek@google.com> Auto-Submit: Carlos Amedee <carlos@golang.org> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> (cherry picked from commit 4c75671) Reviewed-on: https://go-review.googlesource.com/c/go/+/656815 Reviewed-by: Cherry Mui <cherryyz@google.com>
1 parent bd1bc8a commit 4524009

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/runtime/example_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package runtime_test
66

77
import (
88
"fmt"
9+
"os"
910
"runtime"
1011
"strings"
1112
)
@@ -59,3 +60,36 @@ func ExampleFrames() {
5960
// - more:true | runtime_test.ExampleFrames.func3
6061
// - more:true | runtime_test.ExampleFrames
6162
}
63+
64+
func ExampleAddCleanup() {
65+
tempFile, err := os.CreateTemp(os.TempDir(), "file.*")
66+
if err != nil {
67+
fmt.Println("failed to create temp file:", err)
68+
return
69+
}
70+
71+
ch := make(chan struct{})
72+
73+
// Attach a cleanup function to the file object.
74+
runtime.AddCleanup(&tempFile, func(fileName string) {
75+
if err := os.Remove(fileName); err == nil {
76+
fmt.Println("temp file has been removed")
77+
}
78+
ch <- struct{}{}
79+
}, tempFile.Name())
80+
81+
if err := tempFile.Close(); err != nil {
82+
fmt.Println("failed to close temp file:", err)
83+
return
84+
}
85+
86+
// Run the garbage collector to reclaim unreachable objects
87+
// and enqueue their cleanup functions.
88+
runtime.GC()
89+
90+
// Wait until cleanup function is done.
91+
<-ch
92+
93+
// Output:
94+
// temp file has been removed
95+
}

0 commit comments

Comments
 (0)