小言_互联网的博客

lua程序设计第26章使用协程实现多线程练习题答案

471人阅读  评论(0)

练习26.1

local socket = require "socket"
host = "www.lua.org"
file = "/manual/5.3/manual.html"
function download(host,file)
	local c = assert(socket.connect(host,80))
	local count = 0
	local request = string.format("GET %s HTTP/1.0\r\nhost: %s\r\n\r\n",file,host)
	c:send(request)
	while true do
		local s, status  = receive(c)
		count = count + #s
		if status == "closed" then break end
	end
	c:close()
	print(file,count)
end
--[[function receive(connection)
	local s, status, partial = connection:receive(2^10)
	return s or partial, status
end]]

function receive(connection)
	connection:settimeout(0)
	local s, status, partial = connection:receive(2 ^ 10)
	if status == "timeout" then
		coroutine.yield(connection)
	end
	return s or partial, status
end
tasks = {}
function get(host,file)
	local co = coroutine.wrap(function()download(host,file) end)
	table.insert(tasks, co)
end

--function dispatch()
	local i = 1
	while true do
		if tasks[i] == nil then
			if tasks[1] == nil then
				break
			end
			i = 1
		end
		local res = tasks[i]()
		if not res then
			table.remove(tasks,i)
		else
			i = i + 1
		end
	end
end

function dispatch()
	local i = 1
	local timedout = {}
	while true do
		if tasks[i] == nil then
			if tasks[1] == nil then
				break
			end
			i = 1
			timedout = {}
		end
		local res = tasks[i]()
		if not res then
			table.remove(tasks, i)
		else
			i = i + 1
			timedout[#timedout + 1] = res
			if #timedout == #tasks then
				socket.select(timedout)
			end
		end
	end
end



转载:https://blog.csdn.net/qq_44800780/article/details/101446716
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场