[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Strategies for Lua coroutines in C programs?
- From: Thomas Jericke <tjericke@...>
- Date: Fri, 10 Apr 2015 07:54:13 +0200
On 04/10/2015 08:18 AM, Marc Balmer wrote:
I also use your second approach. A coroutine may use 100% CPU if it
other wise it can also tell my scheduler to pause the coroutine for a
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.
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?
Also I think it makes the code more self explaining.