Weakref: can I use it like this?

I want to do some extended processing on an object referred to by a
weakref. This might generate lots of garbage so I don’t want to turn
off garbage collection while I’m doing this. So I’d really like to
get a proper non-weak reference to the weakref-ed object (assuming
it’s not already garbage-collected). Is it safe to do this?

obj = weakref.__getobj__ # will raise error if weakref is invalid
process obj

I’m hoping this will ensure that if the process method is called then
it gets a real reference to the weakref-ed object, so that it can
safely execute even though garbage collection is still on. I’m also
hoping that once the binding of the obj variable goes out of scope
then the object is available for garbage collection again.

Will this work as I expect? Is it thread-safe? Portable across
different Ruby implementations? Have I missed some race condition?

Regards,

Jeremy H.

On 03/07/2010 10:55 AM, Jeremy H. wrote:

it gets a real reference to the weakref-ed object, so that it can
safely execute even though garbage collection is still on. I’m also
hoping that once the binding of the obj variable goes out of scope
then the object is available for garbage collection again.

Will this work as I expect? Is it thread-safe? Portable across
different Ruby implementations? Have I missed some race condition?

I think that’s exactly the way it should be done.

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs