Scheduling code idea

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Scheduling code idea

Simon Davis
Hello,

I've been looking for a way to run a Lua program that continuously executes functions at set intervals. Lua really needs a sleep(millisecs) function. I could write a c library to do this but I came up with the following method that uses coroutines:


t1 = {func1=0,func2=0}
t2 = {func1=0,func2=0}

function sleep(s,c)
 t1[c] = os.time()
 while(t2[c]-(t1[c]+s)<0)do
  coroutine.yield()
  t2[c] = os.time()
 end
end


co1 = coroutine.create(
 function()
  while(true) do
   print('func1')
   sleep(1,"func1")
  end
 end
)

co2 = coroutine.create(
 function()
  while(true) do
   print('func2')
   sleep(2,"func2")
  end
 end
)


coroutineTable = {co1,co2}
co = coroutineTable[1]
i=1
while(true) do
 coroutine.resume(co)
 --This alternates between all the coroutines in coroutineTable
 co = coroutineTable[math.mod(i,table.getn(coroutineTable))+1]
 i=i+1
end



I would be grateful for comments. Does anyone have any better ways?

Thanks,

Simon








--
___________________________________________________
Play 100s of games for FREE! http://games.mail.com/

Reply | Threaded
Open this post in threaded view
|

Re: Scheduling code idea

Diego Nehab-3
Hi,

> I've been looking for a way to run a Lua program that
> continuously executes functions at set intervals. Lua
> really needs a sleep(millisecs) function.

<promotion>
LuaSocket provides one.
</promotion>

Regards,
Diego.
Reply | Threaded
Open this post in threaded view
|

Re: Scheduling code idea

Javier Guerra Giraldez
On Wednesday 12 April 2006 11:55 pm, Diego Nehab wrote:
> Hi,
>
> > I've been looking for a way to run a Lua program that
> > continuously executes functions at set intervals. Lua
> > really needs a sleep(millisecs) function.
>
> <promotion>
> LuaSocket provides one.
> </promotion>

so does HelperThreads; but i guess it's not what Simon had in mind, because it
also provides a sample coroutine scheduler.

--
Javier

attachment0 (207 bytes) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: Scheduling code idea

Petite Abeille
On 4/13/06, Javier Guerra <[hidden email]> wrote:

> On Wednesday 12 April 2006 11:55 pm, Diego Nehab wrote:
> > Hi,
> >
> > > I've been looking for a way to run a Lua program that
> > > continuously executes functions at set intervals. Lua
> > > really needs a sleep(millisecs) function.
> >
> > <promotion>
> > LuaSocket provides one.
> > </promotion>
>
> so does HelperThreads; but i guess it's not what Simon had in mind, because it
> also provides a sample coroutine scheduler.

Alternatively, one could use something as simple as Luiz Henrique de
Figueiredo's lalarm:

"An alarm library for Lua based on signal and SIGALRM."

http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/lalarm.tar.gz


--
Cheers