lua-users home
lua-l archive

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


On 04/10/2015 08:18 AM, Marc Balmer wrote:
In an application that is written in C I am already using Lua for
scripting, now I want to perform certain task in parallel to the main
function (a cash register), e.g. handling certain credit card
transactions in the background.

My first approach was to create the coroutines using lua_newthread() and
keep a list of runnable coroutines.  Then in the main event loop (it's
an X11 application), when there are no X events to process, I would
check if there are runnable coroutines and resume them, if there are.
This immediately led to my application using 100% CPU time ( because
it's constantly calling into Lua).

My second approach, which seems to work well for now, was to return a
number in coroutine.yield(), which is interpreted by the C program as a
interval value in milliseconds.  The C program would then create an
XtInterval and schedule the coroutine to be resumed in the specified
time.  This way a coroutine schedules itself.

What other strategies are being used?  How do others handle coroutines
in hosted programs?

I also use your second approach. A coroutine may use 100% CPU if it wants to, other wise it can also tell my scheduler to pause the coroutine for a certain time. But I don't use the parameter of yield but instead I use a separate Lua function written in C called "Sleep(...)". This sleep function first tells the scheduler how long the coroutine wants to sleep and then calles yield. This way I am still able to use the parameter of yield for something else.

Also I think it makes the code more self explaining.
--
Thomas