Programming in Lua - 9.4
Programming in Lua - 9.4
Programming in Lua - 9.4
Programming in Lua
Part I. The Language
Chapter 9. Coroutines
require "luasocket"
host = "www.w3.org"
file = "/TR/REC-html32.html"
c = assert(socket.connect(host, 80))
c:close()
while true do
end
c:close()
print(file, count)
end
return connection:receive(2^10)
end
coroutine.yield(connection)
end
return s, status
end
-- create coroutine
local co = coroutine.create(function ()
download(host, file)
end)
table.insert(threads, co)
end
function dispatcher ()
while true do
local n = table.getn(threads)
for i=1,n do
table.remove(threads, i)
break
end
end
end
end
host = "www.w3.org"
get(host, "/TR/html401/html40.txt")
get(host,"/TR/2002/REC-xhtml1-20020801/xhtml1.pdf")
get(host,"/TR/REC-html32.html")
get(host,
"/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.txt")
My machine takes six seconds to download those four files using coroutines.
With the sequential implementation,
it takes more than twice that time (15
seconds).
To avoid this behavior, we can use the select function from LuaSocket.
It
allows a program to block while waiting for a status change in
a group of
sockets.
The changes in our implementation are small.
We only have to
change the dispatcher.
The new version is like this:
function dispatcher ()
while true do
local n = table.getn(threads)
local connections = {}
for i=1,n do
table.remove(threads, i)
break
else -- timeout
table.insert(connections, res)
end
end
if table.getn(connections) == n then
socket.select(connections)
end
end
end