Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't add weak ref feature? #64

Open
ClarkGuan opened this issue Oct 20, 2016 · 2 comments
Open

Can't add weak ref feature? #64

ClarkGuan opened this issue Oct 20, 2016 · 2 comments

Comments

@ClarkGuan
Copy link

I heard that can use runtime.SetFinalizer function implement WEAK REF feature.

@nilium
Copy link
Contributor

nilium commented Oct 20, 2016

That wouldn't cover weak references, just finalization.

In order to correctly implement weak references in go-lua, the Lua GC (or some variation of it) would have to be implemented. Right now, go-lua relies on the Go GC, which does not support weak references, to manage memory.

Going back to finalizers, they're something that could be supported if the GC were implemented (via a metatable with a gc metamethod on userdata, same as Lua 5.2). In any case, it wouldn't make sense to use Go GC finalizers (and using them should be mostly discouraged).

@ClarkGuan
Copy link
Author

Please forgive me my poor English!
Yes, I know what you mean about finalization. What i saw is something like the CODE BELOW:

`
import (
"fmt"
"runtime"
"sync/atomic"
"unsafe"
)

type WeakRef struct {
t uintptr
d uintptr
}

func NewWeakRef(v interface{}) WeakRef {
i := (
[2]uintptr)(unsafe.Pointer(&v))
w := &WeakRef{^i[0], ^i[1]}
runtime.SetFinalizer((*uintptr)(unsafe.Pointer(i[1])), func(_ *uintptr) {
atomic.StoreUintptr(&w.d, 0)
w.t = 0
})
return w
}

func (w WeakRef) Get() (v interface{}) {
t := w.t
d := atomic.LoadUintptr(&w.d)
if d != 0 {
i := (
[2]uintptr)(unsafe.Pointer(&v))
i[0] = ^t
i[1] = ^d
}
return
}
`

convert Go pointer to uintptr which not prevent Go object from being collected by GC. Here runtime.SetFinalizer I think only provide a chance to notify us "oh, it has been collected".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants