lua-users home
lua-l archive

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

> -----Original Message-----
> From: [] On
> Behalf Of Austin Einter
> Sent: maandag 14 juli 2014 11:13
> To: Lua mailing list
> Subject: Re: Lua State Thread Safety
> Hi Thijs Schreijer
> I did not understand understand two statements from you.
> 1.  Keep the stuff you need 'anchored' in the lua state, then it will not be
> collected.
> Kindly elaborate what you mean here....

As long as Lua has a reference to an item, the GC will not collect it. So on the C side, you can have elements on the stack, or store them in the registry for example.

Example; a Lua piece of code calls a C function with a userdata, no other references exist. Now when the C function pops the userdata from the stack and stores a pointer locally, the GC might collect it (as there are no references left). The GC will only run when you make some call on the Lua API. But if you unlock now, then another thread can enter, causing the GC to run and collect your userdata. Now when control returns to your first thread, the userdata reference held there is invalid.

To prevent the userdata from becoming invalid, leave it on the stack. Only remove it when you're done with it. This is best practice anyway, yet when using multithreaded solutions it is a must to prevent trouble.

> 2.  BTW; did someone mention that top-posting is considered a bad habit
> around here?
> Are you asking me to write the mail at top of mail chain.., but I found
> mostly all mails are down the line , and so followed, sorry if I understood
> wrongly.

Please don't top-post. When replying, place your comments question in the original message, leaving out the irrelevant parts

> Anyway, I am concluding
> 1. I will have my own lock (semaphore with default count 1), will lock /
> unlock as per my requirement
> 2. With this I assume I would not messup with lua state.
> Austin