Skip to content

Instantly share code, notes, and snippets.

@blanchonvincent
Created September 14, 2019 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blanchonvincent/a247b6c2af559b62f93377b5d7581b7f to your computer and use it in GitHub Desktop.
Save blanchonvincent/a247b6c2af559b62f93377b5d7581b7f to your computer and use it in GitHub Desktop.
Medium - Keep Alive
type File struct { d int }
func main() {
p := openFile("t.txt")
content := readFile(p.d)
println("Here is the content: "+content)
}
func openFile(path string) *File {
d, err := syscall.Open(path, syscall.O_RDONLY, 0)
if err != nil {
panic(err)
}
p := &File{d}
runtime.SetFinalizer(p, func(p *File) {
syscall.Close(p.d)
})
return p
}
func readFile(descriptor int) string {
doSomeAllocation()
var buf [1000]byte
_, err := syscall.Read(descriptor, buf[:])
if err != nil {
panic(err)
}
return string(buf[:])
}
func doSomeAllocation() {
var a *int
// memory increase to force the GC
for i:= 0; i < 10000000; i++ {
i := 1
a = &i
}
_ = a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment