c++ addon: How to prevent GC for event triggered in another thread

124 views
Skip to first unread message

Grant Hutchins

unread,
Oct 14, 2014, 8:04:24 PM10/14/14
to nod...@googlegroups.com
I have a Node ObjectWrap subclass object that handles a uv_async_send from a thread I don't control (from a key-value store library I'm using that can trigger an event at any time). I would like to make sure that if uv_async_send is triggered from this other thread, I can call Ref() on my ObjectWrap so that its v8 object doesn't get GC'ed before the async fires on the main loop.

So far the only way I've gotten things to work is to call Ref() in the constructor of the ObjectWrap, but that means that it never gets GC'ed. I'd prefer that it get GC'ed as normal, except when an event has come in and triggered a uv_async_send that hasn't yet been processed on the v8 main loop.

It seems that I keep running into a race condition between somehow getting the main loop to call Ref() and hoping the GC doesn't fire before that and delete the v8 object and thus my ObjectWrap. Am I correct in assuming that Ref() must be called from the main loop?

Fedor Indutny

unread,
Oct 15, 2014, 8:08:22 AM10/15/14
to nod...@googlegroups.com
Hello!

Every interaction with v8 should happen in main thread. Ref() sounds like something that you may want to do.

--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/35beb9be-7a51-41a9-9c44-7d6ca5d80933%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ben Noordhuis

unread,
Oct 15, 2014, 8:08:27 AM10/15/14
to nod...@googlegroups.com
That's correct, you can only call ObjectWrap::Ref() from the main thread.

It's in theory possible to create a thread-safe ObjectWrap class that
acquires a v8::Locker but that won't help with the race condition you
mention: the object can still be garbage-collected before the call to
ObjectWrap::Ref().

You can make the object weak with ObjectWrap::MakeWeak().
ObjectWrap::MakeWeak() invoke the destructor of your class when the
object is garbage-collected.

Please note that libuv handles must be explicitly closed with
uv_close() and that uv_close() is asynchronous: you cannot call it
from your destructor on an embedded uv_async_t handle because the
lifetime of the handle needs to exceed that of the embedding object.
New the uv_async_t in your constructor and delete it in the OnClose
callback.
Reply all
Reply to author
Forward
0 new messages