Skip to content

Instantly share code, notes, and snippets.

@moriyoshi
Last active August 29, 2015 14:02
Show Gist options
  • Save moriyoshi/df7a9733c3cf0f203607 to your computer and use it in GitHub Desktop.
Save moriyoshi/df7a9733c3cf0f203607 to your computer and use it in GitHub Desktop.
package main
import "os"
type RefcountedFile proxy[*os.File] struct {
f *os.File
refcount int
}
func (f *RefcountedFile) __deref() *os.File {
return f.f
}
func (f *RefcountedFile) add_ref() RefcountedFile {
refcount++ // should be done atomically; this is just an example
return f
}
func (f *RefcountedFile) del_ref() {
refcount-- // should be done atomically; this is just an example
if refcount <= 0 {
f.f.Close()
}
}
func some_routine(rf RefcountedFile) {
defer rf.del_ref()
buf := make([]byte, 4096)
n, err := rf.Read(buf)
// ...
}
func main() {
f, err := os.Open("some_file")
if err != nil {
// do something here
return
}
rf := &RefcountedFile { f, 1 }
defer rf.del_ref()
go some_routine(rf.add_ref())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment