lua-users home
lua-l archive

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


> -----Original Message-----
> From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org]
> On Behalf Of mchalkley@mail.com
> Sent: zaterdag 22 september 2012 18:33
> To: Lua mailing list
> Subject: Re: Basic question about LuaSocket and sleeping
> 
> Matthew,
> 
> Saturday, September 22, 2012, 12:11:19 PM, you wrote:
> 
> > Hi,
> 
> > On 22 September 2012 16:52,  <mchalkley@mail.com> wrote:
> >> What I'm really wondering, though, is how socket reads take place.
> >> For example, I'm trying to keep my program from using any more
> system
> >> resources than possible because it's a monitoring tool, so it
> "sleeps"
> >> most of the time. How does LuaSocket handle reading sockets if I
> have
> >> it sleeping for 10-15 seconds between iterations (checking the
> >> schedule to see if there's anything to do). Does a packet that's
> >> received on a socket the program is listening to interrupt the sleep
> >> cycle, or what? This is such a basic question, I suppose, that it
> >> must be addressed in the documentation somewhere, but I can't find
> it...
> 
> > The function you are looking for is select() (available as
> > socket.select()). It is basically a special kind of sleep from which
> > the process can be woken up by events on sockets:
> > http://w3.impa.br/~diego/software/luasocket/socket.html#select
> 
> Thanks!  I'll play with a test using select() instead of sleep(), and
> learn how that works...

Select takes a list of sockets to write to and a list of sockets to read
from. The OS blocks the thread (no CPU usage) until the select times out or
one of the listed sockets becomes available for reading/writing (that is:
guaranteed not to block when performing the next read/write, though there
are exceptions). This allows you to wait for incoming IO without using CPU.

Select isn't very hard, but check the part about the timeouts on the sockets
and the select (2 different timeouts). I usually put sockets on 0 timeout
(non-blocking) and set the required timeout be used with select.
For an implementation using timers with a scheduler checkout CopasTimer
(available through LuaRocks). It extends Copas with timer capabilities using
calculated timeouts (when it calls select, it sets the timeout to the first
timer expiring, so it returns upon IO or when a timer is due to be
executed). 
Though Copas is essentially a server (waits for incoming connections), it's
simple to add outgoing connections. I think the method is called addtask()
or newtask() or something similar. The Copas documentation (on github,
master, not released yet) contains an example I added a while ago. Dunno
what you need, but UDP support is also in master, not released yet.

HTH.

Thijs