File tree 1 file changed +34
-0
lines changed 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -6,6 +6,7 @@ package runtime_test
6
6
7
7
import (
8
8
"fmt"
9
+ "os"
9
10
"runtime"
10
11
"strings"
11
12
)
@@ -59,3 +60,36 @@ func ExampleFrames() {
59
60
// - more:true | runtime_test.ExampleFrames.func3
60
61
// - more:true | runtime_test.ExampleFrames
61
62
}
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
+ }
You can’t perform that action at this time.
0 commit comments