lua-users home
lua-l archive

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


On 3.01.2015 10:39, mniip wrote:
Yes, there's currently no concurrency when executing a lua function so work done
in multiple threads isn't faster than if it's done sequentially. However
per-state mutexes...


Per-state mutexes will be quite tricky to implement, as you don't really have per-state variables. You can have a reference to the same table in two coroutines. You can even have access to the same local numeric value from two or more coroutines if you pass a function around that have it as an upvalue.

One way to implement per-state mutexes is for every TValue to have an "owner" state, so you lock that state mutex before dealing with the value. This will probably require huge efforts and will increase size of TValue, which is not good (OK, on 64bit architectures, you can squeeze in 32bit index without size penalty as TValue is being padded to 16 bytes anyway, that is in Lua 5.2).

In any case mutexes are very slow, expensive, require synchronization between all CPUs (which might be cheap if they are all on the same die in a single hardware processor, multiple cores case, but it gets more expensive if you add more dies). And the general rule is that if you keep protecting very small pieces of code, you will not get any benefit out of the multi threading (See 3.2 Overheads in Perfbook - https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html).

Also this kind of concurrency, you are proposing will have many problems. For example this code will now yield unpredictable results if the variable "a" is shared:
a=a+1;
t[a]=newval;

I don't exactly know what is Lanes' approach to multi threading, but I would start different threads with different Lua states. Inside them I would have an userdata value that behaves like a table with accesses to all fields would be serialized and shared between all threads. Of course in this case you will have to copy the values on every access from your own representation to Lua. Atomic add/subtract will be necessary. The same goes for explicit lock/unlock as in some cases you just want to have an atomic transaction involving multiple variables.

Best,
Anton