lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Olivier Galibert kirjoitti 29.7.2008 kello 15:42:

On Tue, Jul 29, 2008 at 05:57:25PM +0530, Vivek Gupta wrote:

I have a multi-threaded application in 'C' which invokes LUA functions. Because of the fact that LUA is a single threaded language I have used a global LUA state and used a mutex to serialize the access to global LUA
state among the multiple threads. But this implementation has a
performance bottleneck because of this serialization aspect.

To get rid of this serialization, is it feasible to maintain LUA state
on a per thread basis? But I can foresee some issues with the LUA
global. We might require synchronizing these LUA global variables. Has
anyone tried this out? Some practical example would really help.

You can create a lua state per thread without any difficulty.  They
just won't share anything, which is not necessarily a problem, it
entirely depends on the specifics of your application.

In particular, how globals are your globals in the lua code?  Could
they be considered thread-local storage and things would still mostly
work, or are they a heavily used method of communication?  In the
second case, then your performance bottleneck is not due to lua, it is
due to having too much non-explicit communications between threads,
and the problem would be identical in C.  In the first case, though,
you can have the small amount of synchronizing communications done by
calling back into C through a number of appropriately designed
userdata objects.


As Olivier suggests, handling shared state in a C userdata shared by the Lua states, with locking, is the easiest solution.

If you have a lot of shared data, you may want to look at the src/ tools.c file of Lanes 2008, which has "inter-state" copy function. It is still under development, but works for 95% of the cases (support for cyclic tables, metatables, and such coming in next revise).

Lanes uses the inter-state copy to keep "deep global" data in special hidden "keeper states". During inter-state copying, you are supposed to have exclusive access to both the involved states.

If you want a "keys ready" approach, require "lanes" from the Lua states you've created yourself, and then do 'h= lanes.linda()' to get Linda communications objects. Tryable version is at LuaForge; if you are using Windows ask me for a patched one.