lua-users home
lua-l archive

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

On Thursday, February 23, 2023 at 02:23:04 AM CST, bil til <> wrote:

> I am talking of cooperative multithreading "inside Lua" (so Lua
> coroutines - just wrapped as my own "tasks"

I'm not sure how that works, since the Task that hands out a "Future" has to wait until the holder of the Future yields control. Unless it's waiting on some sort of I/O or external process? Or maybe I'm misunderstanding this Task model.

In any case, having contemplated the problem for a full minute, the only foolproof solution I can come up with is to put a finalizer on the "Future" object that notifies the creator that it's been dropped on the floor. However, that assumes GC runs in a timely manner, which almost never happens.

A fool-vulnerable approach might be to have the caller explicitly cancel the Future before dropping it. Only fools rely on programmer discipline, though.

Unfortunately there's no such thing as a smart pointer in standard Lua, so there's no barrier to check if a local variable releases a value. You could theoretically intercept '__newindex' on a table or global variable, but that's about it.

If anyone has a tested solution to this I'd be interested. On my long list of projects I'd like to pursue if I ever have infinite free time is Multi-threaded Lua using a Communicating Sequential Processes model, not unlike the example at the back of the most recent _Programming in Lua_. The Future object in that case would be listening on a CSP channel for the response, but it might as well tell the thread at the other end not to bother if someone made a synchronous call but didn't stick around.

Frank Mitchell

 - I think my task library
is quite a bit more easily to handle by user than the Lua coroutine

I do this on a single core embedded STM32 controller with very
restricted RAM. (for e. g. bluetooth this effectively uses a 2-core
system, but with very clear state driven data exchange / no
"concurrent RAM space" data handling which requires semaphore

If you want to support CPU pre-emptive multithreading / hardware
multithreading on several cores e. g. of typical modern Intel PC CPU,
then you would need semaphore handling usually to ensure data
integrity ... . This I complicated and I would usually NOT recommend
to present such "data ambiguity problems" to a Lua user, but handle
this semaphore stuff then exclusively in my C code.

For Lua user in such case I anyway would strongly recommend to keep
with cooperative multihreading on Lua side (and effectively hide the
difficulities of the pre-emptive data handling from the Lua user /
manage the pre-emptive data and thread handling exclusively in my C
"task-library" code)... .