Re: newbie: VM asynchronous control from C Side

  • From: "Claire Lewis" <claire_lewis@xxxxxxxxxxx>
  • To: <luajit@xxxxxxxxxxxxx>
  • Date: Sat, 23 Jun 2012 19:40:51 +0930

Hi my app (C/C++) loads & runs a LUA file…
When I do that calling lua_pcall(,) the "run" action blocks the thread until the VM finishes the execution. This blocked thread represents a problem for lengthy scripts.

There may be other options, but perhaps you could use the debug hooks for this (I'm making the assumption LuaJIT supports them completely...), particularly the "count" hook?

This can give you a periodic call to your hook, though it won't actually return control back to the frame of the pcall. I would consider creating another thread to run the script, then using the hook (or coroutine) in association with a synchronisation semaphore/mutex/event to your main thread perhaps.

There are some potential pitfalls though:

* If you're allowing it to pause execution at arbitrary times during the script, the state of anything the script can access via FFI (or otherwise) is going to be undefined. Unless every single FFI call you provide is atomic, then it's going to get tricky. Either you can't do a lot on the main thread while the script is executing, or you're going to need to lock a lot of stuff; and that's going to open up a deadlock minefield if the script cannot complete while the main thread has paused it.

Explicit synchronisation, such as coroutines, would shift this burden onto the script, such that it ensures the current state modifications are completed before yielding. This may be a plus or a minus, depending who is writing these scripts (In my experience most end-users typically using Lua scripting in apps, tend to not understand threading and synchronisation issues, not really being programmers)

* No matter what you do you're kind of limited to the "suspend" happening during Lua code. Any calls to FFI, or IO, or Lua API functions that may block (or simply take a long time) aren't going to get interrupted.

And I'm sure others I've not thought of off the top of my head.

- Claire


Other related posts: