Re: Sharing a C object across different lua_States

  • From: Mike Pall <mike-1208@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Mon, 27 Aug 2012 15:58:30 +0200

Jeff Slutter wrote:
> I'm curious if the garbage collector is per-lua_State, or across the
> entire process.

Different VM instances are completely independent of each other.

> For example, if I have two lua_State states (StateA & StateB), and
> allocate an ffi struct using in StateA. Then, through some
> means, get that pointer to StateB for it to use, and then drop my only
> reference to it in StateA, will the GC think that data is no longer in
> use and free the resource, or will it see that it is still in use in
> StateB (assuming I hold a reference in the state)?

The former (and it'll probably crash).

> One example of this is in William Adam's [great] blog post here:
> It is obviously working for him (or, so I guess, I know he is on the
> mailing list), but I want to make sure it is a safe idea. Well, at least
> that the GC won't pull the rug out from under me.

Well, you gotta be careful not to let that reference be garbage
collected, of course. Provided you take care of that, then it's
perfectly ok to allocate FFI cdata owned by one state and use it
in another.

As others have pointed out: you need to think about ownership and
which thread or VM is responsible for holding the reference (of GC
objects) or for cleaning up (after malloc).

E.g. if you have a 'main' thread that delegates work to other
threads, then it's easiest if you make it the owner, since it's
usually going to be the last thread to be terminated.


Other related posts: