mirror of https://github.com/golang/go.git
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. 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>
This commit is contained in:
parent
011da163f4
commit
4c75671871
|
|
@ -6,6 +6,7 @@ package runtime_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
@ -59,3 +60,36 @@ func ExampleFrames() {
|
||||||
// - more:true | runtime_test.ExampleFrames.func3
|
// - more:true | runtime_test.ExampleFrames.func3
|
||||||
// - more:true | runtime_test.ExampleFrames
|
// - more:true | runtime_test.ExampleFrames
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExampleAddCleanup() {
|
||||||
|
tempFile, err := os.CreateTemp(os.TempDir(), "file.*")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("failed to create temp file:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ch := make(chan struct{})
|
||||||
|
|
||||||
|
// Attach a cleanup function to the file object.
|
||||||
|
runtime.AddCleanup(&tempFile, func(fileName string) {
|
||||||
|
if err := os.Remove(fileName); err == nil {
|
||||||
|
fmt.Println("temp file has been removed")
|
||||||
|
}
|
||||||
|
ch <- struct{}{}
|
||||||
|
}, tempFile.Name())
|
||||||
|
|
||||||
|
if err := tempFile.Close(); err != nil {
|
||||||
|
fmt.Println("failed to close temp file:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run the garbage collector to reclaim unreachable objects
|
||||||
|
// and enqueue their cleanup functions.
|
||||||
|
runtime.GC()
|
||||||
|
|
||||||
|
// Wait until cleanup function is done.
|
||||||
|
<-ch
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// temp file has been removed
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue